using python subprocess.call to kill all running python files

萝らか妹 提交于 2020-01-06 09:32:58

问题


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.


回答1:


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()



回答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.



来源:https://stackoverflow.com/questions/9654784/using-python-subprocess-call-to-kill-all-running-python-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!