打印未显示在 ipython 笔记本中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25494182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:18:43  来源:igfitidea点击:

Print not showing in ipython notebook

pythonprintingipythonjupyter-notebook

提问by alvas

I am using ipythonnotebook (http://ipython.org/notebook.html) to do a demo and it seems like the print function is not working:

我正在使用ipythonnotebook ( http://ipython.org/notebook.html) 进行演示,但似乎打印功能不起作用:

enter image description here

在此处输入图片说明

The commands in the above picture are rewritten here for clarity.

为清楚起见,上图中的命令在此处重写。

In [1]: 'hello world'
Out [1]: 'hello world'

In [2]: print 'hello world'

In short, there's no print output from the [2].

简而言之,[2].

Does anyone know whether it's a known bug? And does anyone know how to fix it?

有谁知道这是否是一个已知的错误?有谁知道如何解决它?

采纳答案by cnaak

I had a similar printing problem when my first code cell was:

当我的第一个代码单元是:

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

Then I've commented the second and third lines like this:

然后我像这样评论了第二行和第三行:

import sys
#reload(sys)
#sys.setdefaultencoding("utf-8")

Reset the kernel and re-ran the program and now my print statements are working properly.

重置内核并重新运行程序,现在我的打印语句工作正常。

Later on, I've found that when I was first having the printing problem, all print outputs were actually being sent to the ipython console terminal (on my Linux box), instead of being embed on the notebook.

后来,我发现当我第一次遇到打印问题时,所有打印输出实际上都被发送到 ipython 控制台终端(在我的 Linux 机器上),而不是嵌入到笔记本上。

回答by JoostJM

I encountered a similar problem (the reload(sys)was in a package I imported).

我遇到了类似的问题(在reload(sys)我导入的包中)。

My workaround was that at the top of the script, I import sys, and store sys.stdoutin a separate variable, e.g. stdout.

我的解决方法是在脚本的顶部,我导入sys并存储sys.stdout在一个单独的变量中,例如stdout.

Then I import all the other stuff, including the one that calls reload(sys).

然后我导入所有其他内容,包括调用reload(sys).

Then, at the end, I set sys.stdout = stdout, which redirects the output back to the IPython notebook

然后,最后,我设置了sys.stdout = stdout,它将输出重定向回 IPython 笔记本

回答by princelySid

Taking what @JoostJM has said, which works, and putting it as code:

采取@JoostJM 所说的,这是有效的,并将其作为代码:

import sys
stdout = sys.stdout
reload(sys)
sys.setdefaultencoding('utf-8')
sys.stdout = stdout

Changing the default encoding directs the output to the console, this sets it back to the jupyter notebook.

更改默认编码会将输出定向到控制台,这会将其设置回 jupyter 笔记本。