Stdout in IPython notebook vs CLI IPython

老子叫甜甜 提交于 2019-12-02 01:23:40

This is explained here:

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 (Notebook) has a solution for this:

In [1]: %pwd

'/Users/xxx/tmp'

You can also call any shell command:

In [2]: !pwd

'/Users/xxx/tmp'

In the notebook you can also run a whole cell with bash commands:

In [3]: %%bash
        pwd 
        ls

'/Users/xxx/tmp'
file1.txt
file2.txt
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!