using python to kill all running p

2019-08-24 02:07发布


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)  
print 'Killed them all!'

But, of course - my program is also a python program, so eventually, it doesn't reach the print line after calling 'call'.

What can I do in order to avoid my program to kill also itself, while killing all other python processes?


You may want to try cross-platform psutil library:

import os
import psutil

mypid = os.getpid()
for proc in psutil.process_iter():
    if == 'python' and != mypid:


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.