python - 使用管道将打印到 STDERR 的内容从 Jupyter 捕获到 Python 变量中

标签 python ipython jupyter

当我在 jupyter notebook 中运行命令时,我试图捕获打印到 STDERR 的内容。特别是,我使用的是 TensorFlow,它从 C 部分执行 fprintf,通常打印在控制台上,但我想保存到 Python 变量中。

我一直在使用 IPython codebase 的 FDRedirector|它设置 os.pipe 以将输出捕获到 Python 字符串中。

但是,此代码的问题在于它会挂起内核以获得足够大的输出。我怀疑它会在输出超过 65k 时挂起,因为这是 Linux 上的管道缓冲区大小,gdb 显示挂起发生在 write 中。有没有人有适用于更大输出的解决方案?

作为我现在正在做的事情的一个例子,使用 FDRedirector

STDERR = 2
redirect = FDRedirector(STDERR)
import tensorflow as tf
sess = tf.Session("")
node = tf.Print(tf.constant(1), [tf.constant(1)], "longstringlongstring")
def print_to_stderr():
    sess.run(node)   # this prints to stderr
redirect.start();
print_to_stderr()
captured_stderr = redirect.stop()

最后,“captured_stderr”包含打印到 stderr 的所有内容,包括 longstringlongstring。如果您使 longstring 部分更长(>100k),这将卡住。

最佳答案

您可以尝试将输出通过管道传输到一个临时文件——因此没有缓冲区限制:

STDERR=2
STDOUT=1
import os
import sys
import tempfile

class captured:
    def __init__(self, fd=STDERR):
        self.fd = fd
        self.prevfd = None

    def __enter__(self):
        t = tempfile.NamedTemporaryFile()
        print 'Piping your output to ' + t.name
        self.prevfd = os.dup(self.fd)
        os.dup2(t.fileno(), self.fd)
        return t

    def __exit__(self, exc_type, exc_value, traceback):
        os.dup2(self.prevfd, self.fd)

with captured(fd=STDOUT) as tmp:
    os.system('cat 1mbfile.txt');

print "Captured:", open(tmp.name).read()    

请让我知道这是否适合您的目的。不幸的是我没有安装 TF。

Jupyter 本身在向单元格输出 1Mb 时幸存下来:)

关于python - 使用管道将打印到 STDERR 的内容从 Jupyter 捕获到 Python 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41216215/

相关文章:

python - 为什么我的折线图没有显示在 GUI 上

python - django:如何在没有空间的情况下过滤模型字段值?

python - Tensorflow 可视化工具 "Tensorboard"在 Anaconda 下不工作

python - IPython 笔记本 : How to write cell magic which can access notebook variables?

python - 在 (i)python 脚本中从 jupyter 内核获取输出

python - 无法在 Spark 中导入名称 LDA MLlib

python - 在kivy中设置全局字体大小

Python virtualenv --system-site-packages iPython

jupyter-notebook - 如何设置在 VSCode Jupyter Notebook 中渲染的默认 mimetype

python - 用于运行特定单元格的 Jupyter 键盘快捷键