[英]How to capture the prints of a python script being executed from another python script?
我在同一文件夾中有2個腳本script1.py
和script2.py
,script1.py使用Popen調用script2.py(有關詳細信息,請參見下面的代碼),問題是來自script2.py的打印件未在script1中捕獲。 py, print output
和print 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..
根據評論編輯答案
對原始問題進行編輯后,您的代碼看起來正常工作。 我只是將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..
>>>
您的腳本實際上按預期工作。 您可能希望將回溯打印到子流程的stderr,但這不是sys.exit()
工作方式。
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
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管道。 但是,可以從proc
的屬性returncode
確定returncode
。
運行>python script1.py
產生:
detceted ton trop:RORRE return status: 29 Done.. YAY
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.