我正在编写一个脚本,它使用了IPython的嵌入式炮击功能,并且作为一个要求,它必须将stdin/stdout中的所有数据记录到一个文件中。出于这个原因,我决定为它们编写包装器;然而,在关闭流后,我的嵌入式IPython外壳将失去自动完成功能和历史记录功能,在我按箭头按钮时输出如下内容:
In [1]: ^[[A^[[B^[[A^[[C...我猜包装器在某种程度上阻止了IPython识别用于向上、向下、左和右箭头(ESC[#A、ESC[#B、ESC[#C、ESC[#D)的ANSI转义序列。
下面的代码演示了我的问题:
import sys
from time import strftime
import IPython
# Custom IO class for file logging
class StdinLogger (object):
def __init__(self, wrapped, file):
# double-underscore everything to prevent clashes with names of
# attributes on the wrapped stream object.
self.__wrapped = wrapped
self.__file = file
def __getattr__(self, name):
return getattr(self.__wrapped, name)
def readline(self):
str = self.__wrapped.readline()
self.__file.write(str)
self.__file.flush()
return str
# Custom IO class for file logging
class StdoutLogger (object):
def __init__(self, wrapped, file):
# double-underscore everything to prevent clashes with names of
# attributes on the wrapped stream object.
self.__wrapped = wrapped
self.__file = file
def __getattr__(self, item):
return getattr(self.__wrapped, item)
def write(self, str):
self.__file.write(str)
self.__file.flush()
self.__wrapped.write(str)
self.__wrapped.flush()
f = open("LOG-" + strftime("%Y-%m-%d-%H-%M-%S") + ".txt", 'w')
# Initialize the file logger
sys.stdin = StdinLogger(sys.stdin, f)
sys.stdout = StdoutLogger(sys.stdout, f)
# Embed IPython shell
IPython.embed(banner1="", banner2="")对于如何解决这个问题,有什么想法吗?
提前谢谢。
发布于 2016-07-08 22:22:25
@Carreau's (IPython核心开发人员)在Github上对此问题的回应:
问题是,对于提示符工具包,stdout不仅仅是一个流,因为您确实在屏幕上绘制/擦除/重绘,而且由于它使用事件循环和异步完成,您不能认为stdin/out/err足以知道当前状态。 因此,您(很可能)需要连接到prompt_toolkit并覆盖So 100-输入/输出和/或窗口。 在IPython启动时,我们很可能需要额外的钩子来设置它。
https://stackoverflow.com/questions/38255591
复制相似问题