我想复制当你做'git commit'之类的事情时发生的功能。它打开你的编辑器,然后键入一些东西,然后保存/退出,将该文件交给启动编辑器的脚本。从Python中打开vi
我该如何在Python中实现这个功能?
编辑:
感谢您的建议,这里的基础上,答案工作示例:
import os, subprocess, tempfile
(fd, path) = tempfile.mkstemp()
fp = os.fdopen(fd, 'w')
fp.write('default')
fp.close()
editor = os.getenv('EDITOR', 'vi')
print(editor, path)
subprocess.call('%s %s' % (editor, path), shell=True)
with open(path, 'r') as f:
print(f.read())
os.unlink(path)
您可能需要检查subprocess.call的返回码以确保用户没有终止进程。 'returncode = subprocess.call(cmd,shell = True)'然后检查它是否为== 0 – 2014-04-16 11:02:01
我得到'AttributeError:'int'对象没有属性'write''在行'f.write('default' )'。更好地使用'tempfile.mkstemp'似乎就在那里:https://www.logilab.org/blogentry/17873 – 2016-07-19 12:48:46