![](/img/trans.png)
[英]Program not recognising geckodriver in PATH when calling a python file from a bash script
[英]iPython embed() automatically exits when calling script from bash file
我有一个要调试的数据处理管道设置。 管道由一个调用 python 脚本的 bash 脚本组成。
我通常使用 iPython 的 embed() 函数进行调试。 但是,当从 bash 文件调用 python 脚本时, embed() 函数被调用但立即退出,而我无法干预。 当直接从命令行运行相同的 python 程序时,我没有观察到这种行为。 这是预期的行为还是我做错了什么?
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
Type "copyright", "credits" or "license" for more information.
IPython 2.4.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]:
Do you really want to exit ([y]/n)?
'follow up code prints here'
我进行了一些实验以查看行为。 我注意到如果任何祖先进程是终端,IPython 会显示控制台。
以下是/tmp目录中的文件: x.py
import IPython
IPython.embed()
调用文件
/usr/bin/python /tmp/x.py
调用2.sh
/tmp/call.sh
实验 1运行python x.py
确实会打开 IPython shell 并等待。
实验 2运行bash call.sh
也会打开 IPython shell 并等待。
实验 3运行bash call2.sh
也会打开 IPython shell 并等待。
如您所见,您的 IPython.embed 调用有多深并不重要。 它总是启动交互式控制台并等待。
让我们试试当我们 fork 一个新进程时它是否也有效。
叉子.sh
/usr/bin/python /tmp/x.py &
实验4在这种情况下,IPython shell 启动但立即退出。 注意末尾的 &。 它开始了一个不同的过程。 在这种情况下,IPython 无法访问终端,因此正常退出。
我可以像这样复制问题:
# test.py
import IPython
import sys
print(sys.stdin.read())
IPython.embed()
# session
❯ echo 'foo' | python test.py
foo
Python 3.6.8 (default, Oct 7 2019, 12:59:55)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.10.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: Do you really want to exit ([y]/n)?
❯ # I didn't quit on purpose, it happened automatically
STDIN 不是 TTY,所以我认为 IPython 担心入站文本(通过管道)不会是用户输入。 它不希望foo
(来自我上面的例子)涌入 IPython shell 并做一些意想不到的事情。
您可以通过通过tty
命令获取终端 ID 并在完成从管道读取后将 stdin 重定向到调用终端来解决此问题,如下所示:
with open('/dev/pts/16') as user_tty:
sys.stdin=user_tty
IPython.embed()
有关 ttys 的更多信息,请参阅此帖子。 还要注意,如果你把错误的 tty 放在那里,来自其他终端的输入将控制 IPython。
我不确定 IPython 是否有可能知道调用 tty 会是什么,如果它没有被 bash 覆盖成为管道的输出端。
编辑:这是我更简单的解决方法: 如何调试使用标准输入和 ipython 的脚本?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.