On Windows, I am terminating Popen subprocess if it runs too long.
Is there any way to collect output and error stream before kill
is invoked?
I create a sample child process which prints number 0 to 5 and takes 5 second.
child.py
import time
i = 1
while True:
print(i)
if i == 5:
break
i += 1
time.sleep(1)
Then I create a parent which terminates child after 2 seconds.
parent.py
import subprocess
import time
p = subprocess.Popen(
["C:\..\python.exe", "C:\child.py"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
time.sleep(2)
p.kill()
output, error = p.communicate()
print(output)
My expectation would be that p.communicate()
returns what child has managed to write into output within 2 seconds, i.e. something like b'0rn1rn
. However, the output is empty.
When I reverse the order of methods, then parent waits for child to finish which is not desired.
time.sleep(2)
output, error = p.communicate() # takes 3 seconds
print(output) # returns b'0rn1rn2rn3rn4rn'
p.kill()
not_real_moderator is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.