Stdout in IPython notebook vs CLI IPython

2019-02-26 20:48发布

问题:

Results of commands are not displayed when run from a notebook cell.

From IPython notebook:

os.system("pwd")
0 <-- no errors

From IPython invoked from CLI:

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

I expected to see /Users/joe displayed when command runs from a notebook cell. What's missing?

Thank you, I.

回答1:

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


回答2:

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