来自子进程的ipython笔记本输出

时间:2015-01-24 14:58:31

标签: python ipython ipython-notebook

使用ipython notebook时,subprocess生成的子进程的输出永远不会显示在笔记本本身中。例如,这个单元格

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

仅显示0作为输出,hello打印在启动ipython的终端上。

我可以调整任何配置参数,以便子进程的输出显示在笔记本中吗?


实际上,自定义python c扩展也会吞下它们的输出。有什么问题吗?

3 个答案:

答案 0 :(得分:6)

from subprocess import Popen, PIPE
p = Popen (['echo', 'hello'], stdout=PIPE)
out = p.communicate ()
print (out)
(b'hello\n', None)

您也可以查看stderr,类似地

答案 1 :(得分:5)

如果要捕获输出,请使用check_outputcheck_call返回退出代码。

import subprocess
print subprocess.check_output(['echo', 'hello'])

答案 2 :(得分:0)

来自python3.5 +

我觉得我应该添加一个更好的答案。 subprocess模块现在提供run方法,该方法根据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'
相关问题