gpt4 book ai didi

Python readline 模块在导入期间打印转义字符

转载 作者:太空狗 更新时间:2023-10-29 21:11:15 26 4
gpt4 key购买 nike

我在 Fedora 17 上使用带有 Python 2.7.3 的 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 脚本中运行此片段,您将看到在 suppress_output 上下文中,print 语句确实是抑制,但不抑制转义字符。

$ python test.py |less
Begin
ESC[?1034hEnd
(END)

所以这是我的两个问题:

  1. 这个转义符怎么可能通过?
  2. 如何抑制?

最佳答案

这是我正在使用的(诚然基于@jypeter 的回答),仅当输出未转到 tty 时才清除 TERM 环境变量(例如,被重定向到文件):

if not sys.stdout.isatty():

# remember the original setting
oldTerm = os.environ['TERM']

os.environ['TERM'] = ''

import readline

# restore the orignal TERM setting
os.environ['TERM'] = oldTerm

del oldTerm

关于Python readline 模块在导入期间打印转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15760712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com