flamenco
flamenco

Reputation: 2840

Stdout in IPython notebook vs CLI IPython

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.

Upvotes: 3

Views: 1559

Answers (2)

Mike M&#252;ller
Mike M&#252;ller

Reputation: 85462

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

Upvotes: 4

elyase
elyase

Reputation: 40973

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

Upvotes: 3

Related Questions