YY-LIN 发表于 2017-4-26 12:29:53

python 交互式kill 命令

linux下的firefox老崩溃,每次自动退出后,后台总会有好几个firefox进程在运行,原来的做法是
ps ax | grep firefox
然后用 kill -9 把查出来的进程一个个杀掉
无聊之中,想到用 python做了个交互式的kill

#!/usr/bin/python
from subprocess import *
import os
import sys
def show_ps(ps_name):
if ps_name :
p1 = Popen(["ps","ax"], stdout=PIPE)
p2 = Popen(["grep", ps_name], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()
else :
p1 = Popen(["ps","ax"], stdout=PIPE)
output = p1.communicate()

ps_num={}
for index,line in enumerate(output.split("\n")):
if (line.strip() == ""): continue
pid=line.split()
print "[%d] %s" % (index, line )
ps_num=pid
return ps_num

def main(ps_name):
while True:
ps_num=show_ps(ps_name)
reply = raw_input("enter a number to kill process, enter q quit.")
if reply=="":
break
else :
os.system("kill -9 "+ps_num)

if __name__ == '__main__':
ps_name=None
if len(sys.argv) >= 2 :
ps_name=sys.argv
main(ps_name)
页: [1]
查看完整版本: python 交互式kill 命令