一些 git
命令,例如 git commit
,调用基于命令行的文本编辑器(例如 vim
或 nano
或其他)预先填充一些值,并在用户保存并存在后,对保存的文件执行某些操作。
我应该如何继续将此功能添加到 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/