我遇到了一个有点不寻常的情况。我正在尝试编写交互式控制台的脚本(用于教学/测试目的),并且我尝试了以下操作:
$ 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
>>>
两种情况下如何打印提示呢?
编辑:重定向两者stdout
and stderr
导致绝对不会打印任何内容。所以Python显然“选择”了其中之一stdout
or stderr
。有记录表明这种情况会发生吗?我无法弄清楚Python源代码中实际上是如何完成的。
看起来 python 检查是否stdout
is a 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 http://www.delorie.com/gnu/docs/readline/rlman_41.html。该函数的文档没有说明提示的打印位置,但它可能会检查是否stdout
/stderr
are tty
s.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)