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()[0]
else :
p1 = Popen(["ps","ax"], stdout=PIPE)
output = p1.communicate()[0]
ps_num={}
for index,line in enumerate(output.split("\n")):
if (line.strip() == ""): continue
pid=line.split()[0]
print "[%d] %s" % (index, line )
ps_num[index]=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[int(reply)])
if __name__ == '__main__':
ps_name=None
if len(sys.argv) >= 2 :
ps_name=sys.argv[1]
main(ps_name)
ipython更好
使用pkill firefox