我遇到了一种不寻常的情况。我正在尝试编写交互控制台的脚本(用于教学/测试目的),我尝试了以下内容:
$ 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和stderr绝对不会导致打印任何内容。因此Python显然是在“选择”stdout或stderr之一。这有记录在案吗?我不知道在Python源代码中这是如何实现的。
发布于 2013-08-24 15:17:05
好像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行的Sourcecode。
解释器可能在启动时导入readline模块,在这种情况下,PyOS_ReadlineFunctionPointer将被设置为call_readline,后者使用readline库。特别是,它调用rl_callback_handler_install。这个函数的文档没有说明在哪里打印提示符,但是它可能检查stdout/stderr是否是tty的。
https://stackoverflow.com/questions/18419787
复制相似问题