首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python的交互式提示符">>>“输出到哪里?

Python的交互式提示符">>>“输出到哪里?
EN

Stack Overflow用户
提问于 2013-08-24 14:47:36
回答 1查看 507关注 0票数 10

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

代码语言:javascript
复制
$ 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

代码语言:javascript
复制
$ python 2> /dev/null
>>> print 3
3
>>> 

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

编辑:重定向stdoutstderr绝对不会导致打印任何内容。因此Python显然是在“选择”stdoutstderr之一。这有记录在案吗?我不知道在Python源代码中这是如何实现的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-08-24 15:17:05

好像python检查stdout是否是tty

代码语言:javascript
复制
/* 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的。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18419787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档