我有一个 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/