【发布时间】:2016-07-07 21:28:44
【问题描述】:
我正在编写一个使用 IPython 的嵌入式脱壳功能的脚本,作为要求,它必须将 stdin/stdout 中的所有数据记录到一个文件中。出于这个原因,我决定为它们编写包装器;然而,在切换流之后,我的嵌入式 IPython shell 失去了它的自动完成和历史功能,当我按下箭头按钮时输出如下内容:
In [1]: ^[[A^[[B^[[A^[[C...
我猜测包装器会以某种方式阻止 IPython 识别用于向上、向下、向左和向右箭头的 ANSI 转义序列(ESC[#A、ESC[#B、ESC[#C、ESC[#D)。
这是演示我的问题的代码:
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="")
关于如何解决这个问题的任何想法?
提前致谢。
【问题讨论】:
标签: python linux ipython getattr