gpt4 book ai didi

python - 从 bash 文件调用脚本时,iPython embed() 自动退出

转载 作者:行者123 更新时间:2023-12-04 17:54:44 25 4
gpt4 key购买 nike

我有一个要调试的数据处理管道设置。管道由调用 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'

最佳答案

我可以像这样重现这个问题:

# 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(来 self 上面的示例)涌入 IPython shell 并做一些意想不到的事情。

您可以通过 tty 命令获取您的终端 ID,并在它完成从管道读取后将 stdin 重定向到调用终端来解决这个问题,如下所示:

with open('/dev/pts/16') as user_tty:
sys.stdin=user_tty
IPython.embed()

有关 ttys 的更多信息,请参阅 this post .另请注意,如果您将错误的 tty 放在那里,来自某些其他终端的输入将控制 IPython。

如果没有被 bash 覆盖为管道的输出端,我不确定 IPython 是否有可能知道调用的 tty 是什么。

编辑:这是我的更简单的解决方法:How do I debug a script that uses stdin with ipython?

关于python - 从 bash 文件调用脚本时,iPython embed() 自动退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41243550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com