Skip to content

Instantly share code, notes, and snippets.

@pida42
Created October 13, 2020 10:15
Show Gist options
  • Save pida42/ae78d582d93d6dadfe087c8688a0ea40 to your computer and use it in GitHub Desktop.
Save pida42/ae78d582d93d6dadfe087c8688a0ea40 to your computer and use it in GitHub Desktop.
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