python - 我如何从像 git 那样的命令行程序调用文本编辑器?

标签 python linux command-line-interface

一些 git 命令,例如 git commit,调用基于命令行的文本编辑器(例如 vimnano 或其他)预先填充一些值,并在用户保存并存在后,对保存的文件执行某些操作。

我应该如何继续将此功能添加到 Linux 上类似 Python 的命令行程序?


如果它不使用 Python,请不要停止给出答案,我会对通用的抽象答案或另一种语言的代码形式的答案感到非常满意。

最佳答案

解决方案将取决于您拥有的编辑器、可能在哪个环境变量中找到编辑器以及编辑器是否采用任何命令行参数。

这是一个简单的解决方案,适用于 Windows,无需任何环境变量或编辑器的命令行参数。根据需要进行修改。

import subprocess
import os.path

def start_editor(editor,file_name):

    if not os.path.isfile(file_name): # If file doesn't exist, create it
        with open(file_name,'w'): 
            pass

    command_line=editor+' '+file_name # Add any desired command line args
    p = subprocess.Popen(command_line)
    p.wait()

file_name='test.txt' # Probably known from elsewhere
editor='notepad.exe' # Read from environment variable if desired

start_editor(editor,file_name)

with open(file_name,'r') as f: # Do something with the file, just an example here
    for line in f:
        print line

关于python - 我如何从像 git 那样的命令行程序调用文本编辑器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26108544/

相关文章:

python - 使用 Python 查找排列和组合

linux - 两个linux嵌入式设备如何在以太网上通信

linux - 如何使用video4linux2录制网络摄像头视频信号?

linux - 在 Linux 中,我正在寻找一种方法,让一个进程通过阻塞向另一个进程发出信号

python - 使用 Python 更新之前打印的行(在 CLI 中)?

python - 将数据拟合到 DecisionTreeRegressor 时出现 KeyError

python - 在字符串 "BANANA"中使用 count 来使用 python 的 str.count() inbuild 函数查找 "ANA"作为子字符串时出现错误

erlang - Elixir 或 Erlang 通过隐藏输入提示输入密码

php - 命令行指令解析

Python的argparse从几个可选参数中选择一个