Skip to content Skip to sidebar Skip to footer

Using Python Subprocess.call To Kill All Running Python Files

I'm trying to kill (on a demand) all the python processes that are running at the moment. I was using this command: from subprocess import call call('pkill python', shell=True)

Solution 1:

You may want to try cross-platform psutil library:

import os
import psutil

mypid = os.getpid()
forprocin psutil.process_iter():
    ifproc.name == 'python'andproc.pid != mypid:proc.kill()

Solution 2:

If you call out to pgrep python you'll be able to read in the pids (process identifiers) of all the running python processes. You'll probably want subprocess.check_output for this.

Then you can run through the pids killing each (using os.kill) except for the one that matches your own pid, which you find using os.getpid.

Post a Comment for "Using Python Subprocess.call To Kill All Running Python Files"