Created
October 13, 2020 10:15
-
-
Save pida42/ae78d582d93d6dadfe087c8688a0ea40 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import subprocess | |
import time | |
## If the parent process is ignoring that output, | |
## the Popen call cannot destroy the process as it has data sitting in a pipe and generates zombie processes. | |
#p = subprocess.Popen('ls -l /tmp', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | |
#time.sleep(10) | |
## --- | |
## Right way how to use subprocess Popen without zombie processes after | |
with subprocess.Popen('ls -l /tmp', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p: | |
try: | |
std_out, std_err = p.communicate(timeout=5) | |
except subprocess.TimeoutExpired: | |
p.kill() | |
std_out, std_err = p.communicate() | |
except: | |
p.kill() | |
p.wait() | |
raise | |
time.sleep(10) | |
return_code = p.poll() | |
print(return_code) | |
print(std_out.decode('ascii').strip()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment