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?

Siyuan Ren
  • 7,573
  • 6
  • 47
  • 61

3 Answers3

6

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

import subprocess
print subprocess.check_output(['echo', 'hello'])
Amit
  • 19,780
  • 6
  • 46
  • 54
  • 1
    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. – Siyuan Ren Jan 24 '15 at 16:23
  • In Python3: print(subprocess.check_output(['echo', 'hello'])) – vwvan Dec 06 '18 at 06:56
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

Fred Mitchell
  • 2,145
  • 2
  • 21
  • 29
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'
Fred Mitchell
  • 2,145
  • 2
  • 21
  • 29