我正在尝试实现raw_input()的替换,它将使用vim等可配置文本编辑器作为用户的接口。在
理想的工作流程如下:您的python脚本正在运行,并调用my_raw_input()。在
Vim(或emacs、gedit或任何其他文本编辑器)打开一个空白文档
在文档中键入一些文本,然后保存并退出
python脚本继续运行,文件的内容作为my_raw_input()的返回值。在
如果您熟悉git,这是使用git commit时的经验,其中编辑器是通过core.editor配置的。其他实用程序,如crontab -e也会这样做。在
最后,我希望这个my_raw_input()函数也接受一个带有默认输入内容的可选字符串,然后用户可以对其进行编辑。在
迄今为止的研究os.exec用editor命令替换当前进程,但不返回。也就是说,当vim启动时,python脚本就会退出。在
popen不以交互方式启动子进程,没有显示用户界面。在
{cd4{to write{stdin>命令行中没有参数。在
我看了看code for git,我根本看不懂。在
这可能吗?在
编辑
到目前为止答案不错。我还发现mecurial code也在做同样的事情。我还通过查看crontab code给出了一个例子,但与某些响应相比,它看起来没有必要复杂。在#!/usr/bin/python
import os
import tempfile
def raw_input_editor(default=None, editor=None):
''' like the built-in raw_input(), except that it uses a visual
text editor for ease of editing. Unline raw_input() it can also
take a default value. '''
editor = editor or get_editor()
with tempfile.NamedTemporaryFile(mode='r+') as tmpfile:
if default:
tmpfile.write(default)
tmpfile.flush()
child_pid = os.fork()
is_child = child_pid == 0
if is_child:
os.execvp(editor, [editor, tmpfile.name])
else:
os.waitpid(child_pid, 0)
tmpfile.seek(0)
return tmpfile.read().strip()
def get_editor():
return (os.environ.get('VISUAL')
or os.environ.get('EDITOR')
or 'vi')
if __name__ == "__main__":
print raw_input_editor('this is a test')