ITeye博客

python 交互式kill 命令

shrek · 2009-05-30 23:57 · python · Markdown

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)


评论(2)

  1. #2 楼 · 鹤惊昆仑 · 2010-01-18 11:23

    ipython更好

  2. #1 楼 · lijunjie · 2009-09-02 11:01

    使用pkill firefox

评论功能维护中,当前仅展示历史评论。