nne*_*neo 11 python python-interactive
我遇到了一些不寻常的情况.我正在尝试编写交互式控制台脚本(用于教学/测试目的),我尝试了以下方法:
$ 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
>>>
Run Code Online (Sandbox Code Playgroud)
3不打印,所以其他一切都打开了stderr.到现在为止还挺好.但后来我们重定向stderr:
$ python 2> /dev/null
>>> print 3
3
>>>
Run Code Online (Sandbox Code Playgroud)
如何在两种情况下打印提示?
编辑:重定向两者stdout并stderr导致绝对无法打印.所以Python显然"选择"其中一个stdout或stderr.记录是否会发生?我无法弄清楚这是如何在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);
Run Code Online (Sandbox Code Playgroud)
源代码来自Parser/myreadline.c第 194 行左右。
解释器有可能readline在启动时导入模块,在这种情况下PyOS_ReadlineFunctionPointer将设置为call_readline,它使用该readline库。特别是它调用rl_callback_handler_install. 该函数的文档没有说明提示符的打印位置,但它可能会检查stdout/是否stderr为ttys。