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.

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

@flamenco Did you try one of these approaches?
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

3 Comments

In principle, ipython notebook could have redirected stdout to a socket (.fileno()) (on posixy systems) and displayed that).
@elyase: Can you expand on why Python does not know about the stdout when invoked from a notebook?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.