IPython笔记本中的Stdout与CLI IPython相比 [英] Stdout in IPython notebook vs CLI IPython
问题描述
从笔记本单元格运行时,不显示命令结果。
Results of commands are not displayed when run from a notebook cell.
来自IPython笔记本:
From IPython notebook:
os.system(pwd)
0
< - 没有错误
os.system("pwd")
0
<-- no errors
来自IPython的调用来自CLI:
From IPython invoked from CLI:
在[15]中:os.system(pwd)
/ Users / joe
Out [15]:0
< - 没有错误
In [15]: os.system("pwd")
/Users/joe
Out[15]: 0
<-- no errors
当命令从笔记本单元格运行时,我预计会看到 / Users / joe
。
有什么遗漏?
I expected to see /Users/joe
displayed when command runs from a notebook cell.
What's missing?
谢谢你,
我。
Thank you, I.
推荐答案
此处解释了这一点:
当你执行os.system时,它不会从新的
进程中捕获stdout / stderr。在终端中,这是有效的,因为stdout和stderr只是
直接进入终端,没有Python知道它们。
在笔记本中,它没有,因为内核只能转发它知道的
stdout / stderr。
When you do os.system, it's not capturing stdout/stderr from the new process. In the terminal, this works, because stdout and stderr just go directly to the terminal, without Python ever knowing about them. In the notebook, it doesn't, because the kernel can only forward stdout/stderr that it knows about.
问题的解决方案是使用子流程
:
The solution to the problem is to use subprocess
:
>>> import subprocess
>>> subprocess.check_output(["pwd"])
/Users/joe
这篇关于IPython笔记本中的Stdout与CLI IPython相比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!