Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 275
flamenco Avatar asked May 15 '26 22:05

flamenco


2 Answers

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
like image 120
Mike Müller Avatar answered May 17 '26 11:05

Mike Müller


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
like image 22
elyase Avatar answered May 17 '26 11:05

elyase