Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture the prints of a python script being executed from another python script?

Tags:

python

popen

I have 2 scripts script1.py and script2.py in the same folder ,script1.py calls script2.py using Popen(See code below for details),issue is that the prints coming from script2.py is not being captured in script1.py,print output and print error doesn't print a thing in the code below? what am I missing here? how do I capture the prints from 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)

OUTPUT:-

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


Done..
like image 272
carte blanche Avatar asked Feb 13 '26 13:02

carte blanche


1 Answers

Edited answer based on comments

Looks like after the edits you made to the original question, Your code is working correctly. I just put output= in front of print statement to check that.

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.."

** OUTPUT: **

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..
>>> 
like image 71
Anil_M Avatar answered Feb 17 '26 07:02

Anil_M