>>"输出到哪里?-6ren"> >>"输出到哪里?-我遇到了一个有点不寻常的情况。我正在尝试编写交互式控制台的脚本(用于教学/测试目的),我尝试了以下操作: $ python > /dev/null Python 2.7.3 (v2.7.3:70274-6ren">
gpt4 book ai didi

python - Python的交互提示 ">>>"输出到哪里?

转载 作者:太空狗 更新时间:2023-10-29 18:08:45 25 4
gpt4 key购买 nike

我遇到了一个有点不寻常的情况。我正在尝试编写交互式控制台的脚本(用于教学/测试目的),我尝试了以下操作:

$ python > /dev/null
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print 3
>>>

3 未打印,因此很明显其他所有内容都在 stderr 上。到目前为止,一切都很好。但随后我们重定向 stderr:

$ python 2> /dev/null
>>> print 3
3
>>>

这两种情况如何打印提示?

编辑:重定向 stdoutstderr 绝对不会打印任何内容。所以 Python 显然“选择”了 stdoutstderr 之一。有记录吗?我无法弄清楚这在 Python 源代码中实际上是如何完成的。

最佳答案

似乎 python 检查 stdout 是否是 tty:

/* This is needed to handle the unlikely case that the
* interpreter is in interactive mode *and* stdin/out are not
* a tty. This can happen, for example if python is run like
* this: python -i < test1.py
*/
if (!isatty (fileno (sys_stdin)) || !isatty (fileno (sys_stdout)))
rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt);
else
rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout,
prompt);

源代码来自 Parser/myreadline.c 第 194 行。

解释器有可能在启动时导入了readline模块,在这种情况下,PyOS_ReadlineFunctionPointer将被设置为call_readline,它使用readline 库。特别是它调用 rl_callback_handler_install .该函数的文档没有说明打印提示的位置,但它可能会检查 stdout/stderr 是否为 tty

关于python - Python的交互提示 ">>>"输出到哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18419787/

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