Ale*_*lex 8 python import stdout readline io-redirection
我在readlineFedora 17中使用带有Python 2.7.3 的模块.我对Ubuntu 12.10没有这个问题.
在此期间import readline,将显示转义字符.
$ python -c 'import readline' |less
ESC[?1034h(END)
Run Code Online (Sandbox Code Playgroud)
通常当我得到这样的意外输出时,我会使用stdout/stderr重定向到虚拟文件描述符来处理它(例如下面的例子).但这一次,这种方法不起作用.
import sys
class DummyOutput(object):
def write(self, string):
pass
class suppress_output(object):
"""Context suppressing stdout/stderr output.
"""
def __init__(self):
pass
def __enter__(self):
sys.stdout = DummyOutput()
sys.stderr = DummyOutput()
def __exit__(self, *_):
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
if __name__ == '__main__':
print 'Begin'
with suppress_output():
# Those two print statements have no effect
# but *import readline* prints an escape char
print 'Before importing'
import readline
print 'After importing'
# This one will be displayed
print 'End'
Run Code Online (Sandbox Code Playgroud)
如果在test.py脚本中运行此代码段,您将看到在suppress_output上下文中,print语句确实被抑制,但不是转义字符.
$ python test.py |less
Begin
ESC[?1034hEnd
(END)
Run Code Online (Sandbox Code Playgroud)
所以这是我的两个问题:
回答第一个问题:更改sys.stdout实际上并不影响stdout 的文件描述符指向的文件,而是影响 Python 认为 stdout 的高级文件对象。换句话说,更改sys.stdout会影响您的 Python 代码,但(通常)不会影响您可能使用的任何编译扩展(例如 readline 模块)。sys.stderr所有这些也适用。
回答第二个问题:你可以按照这个答案的建议进行操作(这应该很容易移植到Python)。尽管评论中的建议听起来是更好的方法。