我试图避免像这样终止进程:
import subprocess
command = "pkill python"
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
但是相反,我试图杀死一个特定的进程,而不是所有的python进程。假设process命令称为“ python test.py”,我想杀死该命令,而其他python进程保持完整。不知道我该怎么做。
平台是Linux / Ubuntu
澄清一下,这就是我执行ps -aux |时要完成的工作。grep“ python”我看到了:
sshum 12115 68.6 2.7 142036 13604 pts/0 R 11:11 0:13 python test.py &
sshum 12128 0.0 0.1 11744 904 pts/0 S+ 11:12 0:00 grep --color=auto test.py
我想杀死进程12115,但是我不确定如何在不杀死所有其他python进程的情况下进行此操作。
编辑:这是我想出的解决方案,但它看起来并不特别优雅...
command = "ps aux"
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output = process.communicate()[0].split("\n")
try:
for p in output:
if "python test.py" in p:
l = p.split(" ")
l = [x for x in l if x!='']
pid = int(l[1])
os.kill(pid, 9)
except:
pass
解决方案
pgrep(-f)中有一个标志,它允许在整个命令行中搜索进程,而不仅仅是名称。
ps aux|grep python尝试重现结果时在我的机器上的输出:
shadowk+ 1194 2.4 0.5 354240 70748 ? S 11:29 0:46 /usr/bin/python /usr/share/chronoslnx/main.py
shadowk+ 1239 0.1 0.6 508548 84080 ? Sl 11:29 0:03 /usr/bin/python2 /usr/share/kupfer/kupfer.py
shadowk+ 1245 0.0 0.4 296732 60956 ? S 11:29 0:00 /usr/bin/python2 -O /usr/share/wicd/gtk/wicd-client.py --tray
shadowk+ 2279 99.7 0.0 22800 7372 pts/3 R+ 12:00 0:30 /usr/bin/python ./test.py
shadowk+ 2289 0.0 0.0 10952 2332 pts/0 S+ 12:01 0:00 grep --color=auto python
就我而言,以下任何命令都将获取正在运行的./test py文件的PID:
pgrep -f 'python ./test.py'
pgrep -f 'test.py'
第二个代码更接近您要寻找的代码,因此调整后的代码如下所示(对于Python 2.x,您只需要从e.output中删除.decode()调用,并删除获取PID的调用):
import subprocess
import os
try:
needed_pid=subprocess.check_output(['pgrep','-f','test.py']).decode()
except subprocess.CalledProcessError as e:
print("pgrep failed because ({}):".format(e.returncode) , e.output.decode())
else:
try:
os.kill(int(needed_pid), 9)
print("We killed test.py!")
except ProcessLookupError as e:
print("We tried to kill an old entry.")
except ValueError as e:
print("Well, there's no test.py...so...yeah.")
如果您想直接调用pkill进行相同的操作,也可以像这样更简单地执行此操作:
import subprocess
subprocess.call(['pkill', '-f', 'test.py'])