如何捕获从另一个python脚本执行的python脚本的打印?

时间:2016-10-12 16:16:20

标签: python popen

我在同一文件夹中有2个脚本script1.pyscript2.py,script1.py使用Popen调用script2.py(详见下面的代码),问题是来自script2.py的打印件未在script1.py中捕获,print outputprint error在下面的代码中没有打印出来的东西?我在这里想念的是什么?如何从script2.py中捕获打印件?

script1.py

import subprocess
from subprocess import Popen, PIPE, STDOUT
def func1 ():
    cmd = "python script2.py"
    proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
    (output, error) = proc.communicate()
    print output
    print error

func1()
print "Done.."

script2.py

import sys
print "ERROR:port not detected"
sys.exit(29)

输出: -

C:\Dropbox>python script1.py
ERROR:port not detected


Done..

2 个答案:

答案 0 :(得分:3)

根据评论编辑回答

在对原始问题进行编辑后,您的代码工作正常。 我只是将output=放在print语句前面来检查。

import subprocess
from subprocess import Popen, PIPE, STDOUT
def func1 ():
    cmd = "python script2.py"
    proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
    (output, error) = proc.communicate()
    print "output=",output
    print error

func1()
print "Done.."

**输出:**

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
output= ERROR:port not detected



Done..
>>> 

答案 1 :(得分:1)

您的脚本实际上是按预期工作的。您可能希望将回溯打印到子流程的stderr,但这不是sys.exit()的工作方式。

script1.py

import subprocess
from subprocess import Popen, PIPE, STDOUT
def func1 ():
    cmd = "python script2.py"
    proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
    (output, error) = proc.communicate()
    print output[::-1] #prints reversed message proving print is called from script1 not script2
    print error #prints nothing because there is no error text (no error was raised only system exit)
    print 'return status: '+str(proc.returncode) #this is what sys.exit() modifies
func1()
print "Done.. YAY" #done prints after call

script2.py

import sys
print "ERROR:port not detected"
sys.exit(29) #does not print traceback (or anything) only sets return code
print "Done.." #never prints because python interpreter is terminated

当script1将script2作为子进程调用时,script2将它的第一个语句输出到stdout管道,然后以返回码29退出。返回代码为0的系统出口被视为成功返回,因此,除非您专门调用引发错误的内容,否则不会向stderr管道打印任何内容。但是,返回代码可以从returncode的<{1}}属性中确定。

运行proc会产生:

detceted ton trop:RORRE

return status: 29
Done.. YAY