例如,某些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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句