Python小工具:查看进程与杀死进程

Ubuntu环境下经常能遇到清除pid的工作,后面可以试试我这个小工具啦~

输入一个进程名称或关键字,展示与输入相关的进程信息,按需杀死进程

废话不多说,直接上才艺

import os


def find_pid(process_name):
    grep_ps_cmd = "ps -ef | grep {} | grep -v grep".format(process_name)
    process_res = os.popen(grep_ps_cmd).read()
    for pr in process_res.split("\n"):
        print(pr)


def kill_pid(pid):
    kill_cmd = "kill -9 {}".format(pid)
    os.system(kill_cmd)

    check_pid_is_kill(pid)

def check_pid_is_kill(pid):
    recheck_res = os.popen("ps -ef | grep " + pid + " | grep -v grep").read()
    if recheck_res == "":
        print("进程清除成功")
    else:
        print("进程清除失败,尝试使用sudo~")

def kill_by_ps(ps):
    grep_ps_cmd = "ps -ef | grep " + ps + " | grep -v grep | awk '{print $2}'"
    process_res = os.popen(grep_ps_cmd).read()
    for pr in process_res.split("\n"):
        print("将要清除的进程号是:", process_res)
        kill_pid(pr)



def menu():
    print("*" * 10 + "Menu" + "*" * 10 + "\n")
    print("1. 查看进程信息(可以输入进程名称或进程号)\n")
    print("2. 根据pid杀死进程\n")
    print("3. 根据进程关键字杀死全部进程(慎用可能会误清)\n")
    print("按下 Ctrl+C 退出\n")


if __name__ == '__main__':
    while True:
        menu()
        case = input("请输入你要进行的操作代号: \n").strip()
        if case == "1":
            ps_name = input("请输入进程名称或pid:\n")
            find_pid(ps_name.strip())
        elif case == "2":
            pid_num = input("请输入进程号:\n").strip()
            kill_pid(pid_num)
        elif case == "3":
            ps_name = input("请输入进程名称:\n")
            kill_by_ps(ps_name)

菜单:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值