如何从 python 脚本启动编辑器(例如 vim)? [英] How to launch an EDITOR (e. g. vim) from a python script?
问题描述
我想在 python 脚本中调用一个编辑器来征求用户的输入,就像 crontab e
或 git commit
一样.
I want to call up an editor in a python script to solicit input from the user, much like crontab e
or git commit
does.
这是我目前运行的片段.(将来,我可能会使用 $EDITOR 而不是 vim,以便人们可以根据自己的喜好进行自定义.)
Here's a snippet from what I have running so far. (In the future, I might use $EDITOR instead of vim so that folks can customize to their liking.)
tmp_file = '/tmp/up.'+''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6))
edit_call = [ "vim",tmp_file]
edit = subprocess.Popen(edit_call,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True )
我的问题是,通过使用 Popen,它似乎使我的带有 python 脚本的 i/o 无法进入 vim 的运行副本,而且我找不到将 i/o 传递给 vim 的方法.我收到以下错误.
My problem is that by using Popen, it seems to keep my i/o with the python script from going into the running copy of vim, and I can't find a way to just pass the i/o through to vim. I get the following error.
Vim: Warning: Output is not to a terminal
Vim: Warning: Input is not from a terminal
从 python 调用 CLI 程序、将控制权交给它,然后在完成后将其传回的最佳方法是什么?
What's the best way to call a CLI program from python, hand control over to it, and then pass it back once you're finished with it?
推荐答案
调用 $EDITOR 很容易.我写了这样的代码来调用编辑器:
Calling up $EDITOR is easy. I've written this kind of code to call up editor:
import sys, tempfile, os
from subprocess import call
EDITOR = os.environ.get('EDITOR','vim') #that easy!
initial_message = "" # if you want to set up the file somehow
with tempfile.NamedTemporaryFile(suffix=".tmp") as tf:
tf.write(initial_message)
tf.flush()
call([EDITOR, tf.name])
# do the parsing with `tf` using regular File operations.
# for instance:
tf.seek(0)
edited_message = tf.read()
这里的好处是,库处理创建和删除临时文件.
The good thing here is, the libraries handle creating and removing the temporary file.
这篇关于如何从 python 脚本启动编辑器(例如 vim)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!