python - 在 Python 中通过管道传输到脚本时无法启动交互式程序

标签 python subprocess interactive nano

我有一个 python 脚本,需要调用定义的 $EDITOR$VISUAL。当单独调用 Python 脚本时,我可以顺利启动 $EDITOR,但是当我将某些内容通过管道传输到 Python 脚本时,$EDITOR 无法启动推出。现在,我正在使用 nano,它显示

Received SIGHUP or SIGTERM

每次。这似乎是同一个问题described here .

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

编辑:澄清;在程序内部,我没有向编辑器发送管道。代码如下:

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

最佳答案

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

% echo | nano
Received SIGHUP or SIGTERM

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

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

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

关于python - 在 Python 中通过管道传输到脚本时无法启动交互式程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5986544/

相关文章:

python - 我想从子进程中获取 stdout 和 stderr

interactive - git add --interactive "Your edited hunk does not apply"

Python - 执行进程 ->阻塞直到它退出并抑制输出

python - 向子进程发送 'ESC' 或信号

python 2.7 : wmi module: Creating an interactive process on a remote system

javascript - 悬停时,从一组 div 中找到匹配的类,并将类名分配给匹配项 (jquery/js)

python - 如何显示另一个线程拥有的文件?

python - 将编译后的模型存储在 Keras 中?

python - sys.exit(1) 不工作,脚本以代码 0 结尾

python - 无法从字符串中删除换行符