using python subprocess.call to kill all running p

2019-08-24 01:55发布

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?
Thanks.

2条回答
不美不萌又怎样
2楼-- · 2019-08-24 02:18

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.

查看更多
疯言疯语
3楼-- · 2019-08-24 02:26

You may want to try cross-platform psutil library:

import os
import psutil

mypid = os.getpid()
for proc in psutil.process_iter():
    if proc.name == 'python' and proc.pid != mypid:
        proc.kill()
查看更多
登录 后发表回答