从Python打开vi

Sco*_*zer 5 python

我想复制当您执行“ git commit”之类的操作时发生的功能。它将打开您的编辑器,您键入一些内容,然后保存/退出以将该文件交还给启动编辑器的脚本。

如何在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)
Run Code Online (Sandbox Code Playgroud)

men*_*nsi 4

通常的情况是:

  1. 创建一个临时文件,写入默认内容
  2. 启动存储在环境变量“EDITOR”中的命令。这通常是一个 shell 命令,因此它可能包含参数 -> 通过 shell 运行它或相应地解析它
  3. 一旦进程终止,读回临时文件
  4. 删除临时文件

所以像这样:

import os, subprocess, tempfile
f, fname = tempfile.mkstemp()
f.write('default')
f.close()
cmd = os.environ.get('EDITOR', 'vi') + ' ' + fname
subprocess.call(cmd, shell=True)
with open(fname, 'r') as f:
    #read file
os.unlink(fname)
Run Code Online (Sandbox Code Playgroud)