【发布时间】:2013-04-02 09:34:41
【问题描述】:
我在 Python 2.7.3 和 Fedora 17 中使用 readline 模块。我在 Ubuntu 12.10 上没有这个问题。
在import readline 期间,会显示一个转义字符。
$ python -c 'import readline' |less
ESC[?1034h(END)
通常当我得到这样的意外输出时,我使用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'
如果您在test.py 脚本中运行这个sn-p,您将看到在suppress_output 上下文中,print 语句确实被抑制,但不是转义字符。
$ python test.py |less
Begin
ESC[?1034hEnd
(END)
所以这是我的两个问题:
- 这个转义字符怎么可能通过?
- 如何抑制?
【问题讨论】:
-
看起来模块想用转义序列改变终端状态,但这不起作用。你不应该尝试解决这个问题,而是解决它。
-
是的,这里有一个基于 reinout.vanrees.org/weblog/2009/08/14/… 的解决方法。但这并没有回答我的第一个问题:)(我担心这不是很便携,但我可能错了)。
-
我怀疑您的终端和/或 terminfo 数据库导致了这个问题。
-
从我的 MacBook 和
TERM=xterm-256colorSSH 连接到 RedHat 机器时,我遇到了这个问题。我相信这是一个 readline 设置错误。我现在能做的最好的就是使用export TERM=vt100解决它。 -
相关python bugbugs.python.org/issue19884
标签: python import stdout readline io-redirection