【问题标题】:Wrapping stdin/stdout causes IPython to lose auto completion and history features包装标准输入/标准输出会导致 IPython 失去自动完成和历史功能
【发布时间】:2016-07-07 21:28:44
【问题描述】:

我正在编写一个使用 IPython 的嵌入式脱壳功能的脚本,作为要求,它必须将 stdin/stdout 中的所有数据记录到一个文件中。出于这个原因,我决定为它们编写包装器;然而,在切换流之后,我的嵌入式 IPython shell 失去了它的自动完成和历史功能,当我按下箭头按钮时输出如下内容:

In [1]: ^[[A^[[B^[[A^[[C...

我猜测包装器会以某种方式阻止 IPython 识别用于向上、向下、向左和向右箭头的 ANSI 转义序列(ESC[#AESC[#BESC[#CESC[#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


    【解决方案1】:

    @Carreau(IPython 核心开发人员)在Github 对此问题的回复:

    问题在于,尤其是使用提示工具包标准输出时 而不是一个流,因为你真的在屏幕上绘制/擦除/重绘,并且 因为它使用事件循环和异步完成,你不能考虑 stdin/out/err 足以知道当前状态。

    因此,您将(可能)需要连接到 prompt_toolkit 和 覆盖 vt100 输入/输出和/或 windows 的。

    我们很可能需要额外的钩子来在 IPython 中设置它 启动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      • 2017-12-26
      • 2021-10-20
      • 2013-09-18
      • 2013-06-13
      • 2012-03-16
      • 1970-01-01
      相关资源
      最近更新 更多