简体   繁体   English

IPython Notebook中的Stdout与CLI IPython

[英]Stdout in IPython notebook vs CLI IPython

Results of commands are not displayed when run from a notebook cell. 从笔记本电脑单元运行时,不显示命令结果。

From IPython notebook: 从IPython笔记本:

os.system("pwd")
0 <-- no errors 0 <-没有错误

From IPython invoked from CLI: 从CLI调用的IPython中:

In [15]: os.system("pwd")
/Users/joe
Out[15]: 0 <-- no errors Out[15]: 0 <-无错误

I expected to see /Users/joe displayed when command runs from a notebook cell. 我希望从笔记本电脑单元运行命令时会显示/Users/joe What's missing? 缺少了什么?

Thank you, I. 谢谢你。

This is explained here : 在这里解释:

When you do os.system, it's not capturing stdout/stderr from the new process. 当您使用os.system时,它不是从新进程中捕获stdout / stderr。 In the terminal, this works, because stdout and stderr just go directly to the terminal, without Python ever knowing about them. 在终端中,这是可行的,因为stdout和stderr只是直接进入终端,而Python对此一无所知。 In the notebook, it doesn't, because the kernel can only forward stdout/stderr that it knows about. 在笔记本中则没有,因为内核只能转发它知道的stdout / stderr。

The solution to the problem is to use subprocess : 解决该问题的方法是使用subprocess

>>> import subprocess
>>> subprocess.check_output(["pwd"])
/Users/joe

IPython (Notebook) has a solution for this: IPython(笔记本)对此有一个解决方案:

In [1]: %pwd

'/Users/xxx/tmp'

You can also call any shell command: 您还可以调用任何shell命令:

In [2]: !pwd

'/Users/xxx/tmp'

In the notebook you can also run a whole cell with bash commands: 在笔记本中,您还可以使用bash命令运行整个单元:

In [3]: %%bash
        pwd 
        ls

'/Users/xxx/tmp'
file1.txt
file2.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM