psutil 获取进程信息

def get_progress_pid():
    # 获取任务管理器所有的进程信息
    for p in psutil.process_iter():
        try:
            print('进程名称:', p.name())#显示进程名称
            print('进程运行命令', p.cmdline())#进程运行命令
            print('运行状态:', p.status()) #运行状态
            print('进程pid:', p.pid) #进程pid
            print('父进程pid:', p.ppid()) #父进程pid
            print('父进程:', p.parent()) #父进程
            print('进程bin路径:', p.exe()) #进程bin路径
            print('*'*100)
        except:
            pass

def judge_process_exist(pid=None, port=None):
    # 判断进程是否存在
    if not pid and port:
        port_pid = {}
        for i in psutil.net_connections():
            pid = i.pid
            status = i.status
            port = i.laddr.port
            port_pid[port] = pid
        pid = port_pid.get(port)

    if not pid:
        return
    # 判断进程id是否存在
    if pid in psutil.pids():
        p = psutil.Process(pid)
        return p.name()
    else:
        return None


def get_progress_chrome_path():
    # 获取进程中谷歌浏览器路径
    chrome_path = None
    for p in psutil.process_iter():
        if p.name().lower() == 'chrome.exe' and p.exe():
            chrome_path = p.exe()
            break
    return chrome_path
def kill_progress_port(port=None):
    # 根据端口号杀掉进程
    pids = []
    try:
        find_port = f'netstat -aon | findstr {port}'
        process = subprocess.Popen(find_port, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="gbk",
                                   shell=True)
        text = process.stdout.read()
        text = [i.split(' ') for i in text.split('\n') if i]
        for i in text:
            pid = [u for u in i if u]
            if str(port) in pid[1]:
                pids.append(pid[-1])
    except:
        pass
    # print('pids:', pids)
    pids = list(set(pids))
    # 杀死占用端口的pid
    for pid in pids:
        if str(pid) == '0':
            continue
        find_kill = 'taskkill -f -pid %s' % pid
        # subprocess.Popen(find_kill)
        # os.popen('taskkill /pid ' + str(process_pid) + ' /F')
        try:
            process = psutil.Process(int(pid))
            process.kill()
        except:
            pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值