来自 Jupyter 笔记本的 stdout 重定向正在登陆终端 [英] stdout redirect from Jupyter notebook is landing in the terminal

查看:21
本文介绍了来自 Jupyter 笔记本的 stdout 重定向正在登陆终端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图将我的 Jupyter Notebook 中某些单元的 stdout 重定向到一个带有 this 然后用 this 用于其余单元格.第一组单元格的输出像预期的那样进入文件.取消命令 sys.stdout = sys.__stdout__ 之后的第二组单元格没有输出,似乎什么都不做,但我后来意识到它正在登陆笔记本电脑的终端.

So I was trying to redirect stdout for a some of the cells in my Jupyter Notebook to a file with this and then cancel it with this for the rest of the cells. The output from the first set of cells landed in the file like it was meant to. The second set of cells after the cancel command sys.stdout = sys.__stdout__ was giving no output, appearing to do nothing, but I later realised it was landing in the terminal where the notebook was launched.

它在 Python 解释器中使用完全相同的 Python 完美运行:

It works perfectly in the Python interpreter with exactly the same Python:

(miniconda3-latest) cardamom@pegasus:~/Documents/project1 $ python
Python 3.6.0 |Continuum Analytics, Inc.| (default, Dec 23 2016, 12:22:00) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout = open('stdout.txt', 'w')
>>> print("a")
>>> print("a")
>>> print("a")
>>> sys.stdout = sys.__stdout__
>>> print ("b")
b
>>> print ("b")
b
>>> print ("b")
b
>>> # lots of a's are in the file and no b's

Jupyter notebook 中的类似方法是在终端中给出:

A similar approach in the Jupyter notebook is giving this in the terminal:

[W 22:05:34.192 NotebookApp] 404 GET /nbextensions/widgets/notebook/js/extension.js (127.0.0.1) 1.71ms referer=http://localhost:8889/notebooks/test_stdout.ipynb
b
b
b

如何修改此代码,以便在重置它后,我让 b 出现在通常输出的单元格下,而不是在终端中?

How can this code be adapted so that after resetting it, I get the b's appearing under the cells where the output usually goes instead of in the terminal?

推荐答案

我看到的唯一解释是 sys.stdoutnot sys.__stdout__ 而是一个重新路由/修改的文件对象,以便能够将数据放入单元格中(您的注释表明它是一个 ipykernel.iostream.OutStream 实例).

The only explanation I see is that sys.stdout is not sys.__stdout__ but a rerouted/modified file object in order to be able to put data in cells (your comment indicates that it's a ipykernel.iostream.OutStream instance).

所以不要重置为sys.__stdout__,你应该存储sys.stdout的引用:

So instead of resetting to sys.__stdout__, you should store the reference of sys.stdout:

import sys
old_stdout = sys.stdout
sys.stdout = open('stdout.txt', 'w')
...
sys.stdout = old_stdout

请注意,此方法也适用于标准终端.

Note that this method also works with a standard terminal.

这篇关于来自 Jupyter 笔记本的 stdout 重定向正在登陆终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆