Main script is script.py
, I run two subprocesses when launching script.py
as follows:
#PART ONE:
import subprocess
command = ["python", "first.py"]
command2 = ["python", "second.py"]
n = 5
for i in range(n):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p2 = subprocess.Popen(command2, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
#PART TWO:
while True: #or while p.returncode==None:
output = p.stdout.readline().strip()
print output
if output == 'stop':
print 'success'
p.terminate()
p2.terminate()
break
So basically I'm stopping both when the subprocess p
prints 'stop'. All is fine. I'm trying to make the same thing work, with the difference of launching the two subprocesses in separate terminals, by adding 'xterm','-e'
to command
and command2
respectively. Problem is now with p.stdout.readline().strip()
I don't get access to what p
prints, so I can't stop the subprocesses from the main script script.py
. How should I modify my code (specially #PART TWO) so that using command = ['xterm','-e','python','first.py']
I can still read the outputs and terminate them if 'stop' is printed?
So basically #PART ONE now is:
#PART ONE:
import subprocess
command = ["xterm","-e","python", "first.py"]
command2 = ["xterm","-e","python", "second.py"]
n = 5
for i in range(n):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p2 = subprocess.Popen(command2, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Question is how to modify #PART TWO, so that outputs can be read, and processes terminated given some condition.