从python脚本调用编辑器(vim) [英] call up an EDITOR (vim) from a python script

查看:436
本文介绍了从python脚本调用编辑器(vim)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆