8

When using ipython notebook, the output of child processes spawned by subprocess never shows up in the notebook itself. For example, this cell

import subprocess
subprocess.check_call(['echo', 'hello'])

Only shows 0 as output, and the hello is printed on the terminal where ipython is launched.

Is there any configuration parameters I can tune such that the output of child processes show up in the notebook itself?


Actually custom python c extensions will also have their output swallowed. Is there any fix?

3 Answers 3

6

Use check_output if you want the output captured. check_call returns the exit code.

import subprocess
print subprocess.check_output(['echo', 'hello'])
Sign up to request clarification or add additional context in comments.

2 Comments

The full output is captured after the command has finished when using check_output. The process I want to actually call is long running, and it writes to stdout and stderr a lot of logging information. I want to view these logging information during the execution, so check_output is not the way to go.
In Python3: print(subprocess.check_output(['echo', 'hello']))
6
from subprocess import Popen, PIPE
p = Popen (['echo', 'hello'], stdout=PIPE)
out = p.communicate ()
print (out)
(b'hello\n', None)

You can also look at stderr, similarly

Comments

1

From python3.5+

I feel that I should add a better answer. The subprocess module now supplies the run method which according to the documentation:

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.

from subprocess import run, PIPE

result = run (['echo', 'hello'], stdout=PIPE)
print (result.returncode, result.stdout)

0 b'hello\n'

Comments

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.