在使用Python管道编写脚本时无法启动交互式程序 [英] Cannot Launch Interactive Program While Piping to Script in Python

查看:159
本文介绍了在使用Python管道编写脚本时无法启动交互式程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本,需要调用已定义的$EDITOR$VISUAL.当单独调用Python脚本时,我可以顺利启动$EDITOR,但是当我将某些内容传送到Python脚本时,$EDITOR无法启动.现在,我正在使用nano来显示

I have a python script that needs to call the defined $EDITOR or $VISUAL. When the Python script is called alone, I am able to launch the $EDITOR without a hitch, but the moment I pipe something to the Python script, the $EDITOR is unable to launch. Right now, I am using nano which shows

收到SIGHUP或SIGTERM

Received SIGHUP or SIGTERM

每次. 此处所述.

sinister:Programming [1313]$ echo "import os;os.system('nano')" > "sample.py" 
sinister:Programming [1314]$ python sample.py
# nano is successfully launched here.
sinister:Programming [1315]$ echo "It dies here." | python sample.py 
Received SIGHUP or SIGTERM

Buffer written to nano.save.1

澄清;在程序内部,我没有管道连接到编辑器.代码如下:

Clarification; inside the program, I am not piping to the editor. The code is as follows:

editorprocess = subprocess.Popen([editor or "vi", temppath])
editorreturncode = os.waitpid(editorprocess.pid, 0)[1]

推荐答案

将内容通过管道传输到流程时,管道将连接到该流程的标准输入.这意味着您的终端输入将不会连接到编辑器.大多数编辑器还会检查其标准输入是否为终端( isatty ),哪个不是管道?如果不是终端,他们将拒绝启动.对于nano,这似乎导致它退出并显示您包含的消息:

When you pipe something to a process, the pipe is connected to that process's standard input. This means your terminal input won't be connected to the editor. Most editors also check whether their standard input is a terminal (isatty), which a pipe isn't; and if it isn't a terminal, they'll refuse to start. In the case of nano, this appears to cause it to exit with the message you included:

% echo | nano
Received SIGHUP or SIGTERM

如果您希望能够将其标准输入传递给基于终端的编辑器,则需要以其他方式(例如通过文件)将输入提供给Python脚本.

You'll need to provide the input to your Python script in another way, such as via a file, if you want to be able to pass its standard input to a terminal-based editor.

现在,您已经澄清了您的问题,即您不想将Python进程的stdin附加到编辑器中,可以按如下所示修改代码:

Now you've clarified your question, that you don't want the Python process's stdin attached to the editor, you can modify your code as follows:

editorprocess = subprocess.Popen([editor or "vi", temppath],
                                 stdin=open('/dev/tty', 'r'))

这篇关于在使用Python管道编写脚本时无法启动交互式程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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