3

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.

flamenco
  • 2,702
  • 5
  • 30
  • 46

2 Answers2

4

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
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
3

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
elyase
  • 39,479
  • 12
  • 112
  • 119
  • 1
    In principle, ipython notebook could have [redirected stdout to a socket (`.fileno()`)](http://stackoverflow.com/a/22434262/4279) (on posixy systems) and displayed that). – jfs Dec 29 '14 at 03:37
  • @elyase: Can you expand on why Python does not know about the stdout when invoked from a notebook? – flamenco Dec 29 '14 at 13:19
  • 1
    @flamenco, It doesn't know about it on the terminal either but there you are a least able to see it. Imagine you call a C program which suddenly decides to make a sound, print or draw something in the screen using a low level API, there are workarounds but it is just not trivial to capture it from Python who is not even aware that happened. Python just told the system "run the program", but it can only exert control over the execution up to a certain level. For a more in depth discussion take a look [here](https://github.com/ipython/ipython/issues/1230). – elyase Dec 29 '14 at 14:01