Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Jupyter笔记本输出重定向_Python_Jupyter Notebook_Stdout - Fatal编程技术网

Python Jupyter笔记本输出重定向

Python Jupyter笔记本输出重定向,python,jupyter-notebook,stdout,Python,Jupyter Notebook,Stdout,我想重定向笔记本中每个单元格的输出。这是我试过的 class Logger(): def __init__(self, stdout): self.stdout = stdout def write(self, msg): self.stdout.write('augmented:' + msg) def flush(self): self.stdout.flush() 在一个单元格中,我会动态更改stdout sy

我想重定向笔记本中每个单元格的输出。这是我试过的

class Logger():
    def __init__(self, stdout):
        self.stdout = stdout

    def write(self, msg):
        self.stdout.write('augmented:' + msg)

    def flush(self):
        self.stdout.flush() 
在一个单元格中,我会动态更改
stdout

sys.stdout = Logger(sys.stdout)

但是,下一个执行单元格的输出字符串没有“增强”字符串

您可以使用
contextlib

从contextlib导入contextmanager
导入系统
@上下文管理器
def stdout_重定向器():
类MyStream:
def写入(self,msg):
前缀='augmented:'if msg.strip()else''
旧的stdout.write(前缀+消息)
def冲洗(自):
老花脸
old_stdout=sys.stdout
sys.stdout=MyStream()
尝试:
产量
最后:
sys.stdout=old\u stdout


最好使用
with
语句来管理重定向。如果在您的情况下不可能这样做,那么调用重定向器对象的
\uuuu enter\uuuuu()
\uuu exit\uuuuu()
方法也可以。您还可以将这些重定向程序代码放入IPython中的
pre\u run\u单元格
post\u run\u单元格

IPython中的事件正是我想要的!我不知道那里的存在。