How to kill a python child process created with subprocess.check_output() when the parent dies?

Your problem is with using subprocess.check_output – you are correct, you can’t get the child PID using that interface. Use Popen instead: proc = subprocess.Popen([“ls”, “-l”], stdout=PIPE, stderr=PIPE) # Here you can get the PID global child_pid child_pid = proc.pid # Now we can wait for the child to complete (output, error) = proc.communicate() if … Read more

Python Subprocess.Popen from a thread

You didn’t supply any code for us to look at, but here’s a sample that does something similar to what you describe: import threading import subprocess class MyClass(threading.Thread): def __init__(self): self.stdout = None self.stderr = None threading.Thread.__init__(self) def run(self): p = subprocess.Popen(‘rsync -av /etc/passwd /tmp’.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.stdout, self.stderr = p.communicate() myclass = MyClass() … Read more

Python subprocess .check_call vs .check_output

check_call() returns as soon as /bin/sh process exits without waiting for descendant processes (assuming shell=True as in your case). check_output() waits until all output is read. If ssh inherits the pipe then check_output() will wait until it exits (until it closes its inherited pipe ends). check_call() code example: #!/usr/bin/env python import subprocess import sys import … Read more

Python subprocess.call a bash alias

Update: Thanks for the upvotes for this hack to workaround the problem, I’m glad it’s useful. But a much better answer is tripleee’s, languishing far down the page… If the alias you require is defined in ~/.bashrc, then it won’t get run for a few reasons: 1) You must give the ‘shell’ keyword arg: subprocess.call(‘command’, … Read more

How do you list all child processes in python?

You can’t always log all the sub-processes as they are created, since they can in turn create new processes that you are not aware of. However, it’s pretty simple to use psutil to find them: import psutil current_process = psutil.Process() children = current_process.children(recursive=True) for child in children: print(‘Child pid is {}’.format(child.pid))

Python os.system without the output

Avoid os.system() by all means, and use subprocess instead: with open(os.devnull, ‘wb’) as devnull: subprocess.check_call([‘/etc/init.d/apache2’, ‘restart’], stdout=devnull, stderr=subprocess.STDOUT) This is the subprocess equivalent of the /etc/init.d/apache2 restart &> /dev/null. There is subprocess.DEVNULL on Python 3.3+: #!/usr/bin/env python3 from subprocess import DEVNULL, STDOUT, check_call check_call([‘/etc/init.d/apache2’, ‘restart’], stdout=DEVNULL, stderr=STDOUT)