有没有办法从 python 脚本打开像 vim 或 gedit 这样的文本编辑器,然后将输入的文本从文本编辑器直接重定向回 python 脚本,这样我就可以将它保存在数据库中?诸如 git commit 命令之类的东西会打开外部文本编辑器并在退出时保存提交消息但不保存到文件中。
1 回答
I think you would end up depending too much on $EDITOR specific behaviour without a tempfile. The tempfile module deals with the choice of a tempdir and tempfilename so you will not have to. Try the following.
manedit.py:
import os
import tempfile
import subprocess
data = '6 30 210 2310 30030'
mefile = tempfile.NamedTemporaryFile( delete=False )
# delete=False otherwise delete on close()
mefile.write( data )
mefile.close()
subprocess.call( [ os.environ.get('EDITOR','') or 'vim', mefile.name ] )
# unset EDITOR or EDITOR='' -> default = vim
# block here
mefile = open( mefile.name, 'r' )
newdata = mefile.read()
mefile.close()
os.remove( mefile.name )
print( newdata )
And then try the following commands to verify each scenario. Replace ed with an editor that differs from your $EDITOR
python manedit.py
env EDITOR= python manedit.py
env EDITOR=ed python manedit.py
env -u EDITOR python manedit.py
The pitfall: The script blocks only while EDITOR is running. An editor may just open a new window on an existing editor session and return, suggesting that the manual edit session completed. However I know no such editor.
edit:
If you are interested specifically in vim or you want to see how specific such thing can get, see the following:
http://vimdoc.sourceforge.net/htmldoc/remote.html
http://petro.tanrei.ca/2010/8/working-with-vim-and-ipython.html
http://www.freehackers.org/VimIntegration