Python 进程线程操作

本文介绍如何使用Python库psutil进行进程管理,包括杀死进程及其子进程、获取进程线程ID、根据端口号定位并杀死进程,以及停止指定线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!encoding=utf8
'''
安装
pip install psutil  
资料
https://github.com/giampaolo/psutil  
https://psutil.readthedocs.io/en/latest/ 
'''

import psutil
import ctypes
import inspect


def kill_process(pid):
    '''
    根据父进程pid杀死进程及子进程
    '''
    print(f'终止进程号 {pid} 及所有子进程')
    parent_proc = psutil.Process(pid)
    # recursive = True 递归查找
    for child_proc in parent_proc.children(recursive=True):
        child_proc.kill()
    parent_proc.kill()
   
def get_thread_ids(pid):
    '''
    根据PID 获取进程下所有线程id
    return 线程ID列表
    '''
    p = psutil.Process(pid)
    # 获取当前进程下所有线程
    threads_list = p.threads()
    tid_list = [t.id for t in threads_list]
    return tid_list

def get_process_id_by_port(port):
    '''
    根据端口号获取目标进程ID
    '''    
    for proc in psutil.process_iter():
        # print (proc)
        for c in proc.connections():
            if c.status == psutil.CONN_LISTEN:
                if c.laddr.port == int(port):
                    print(f'port: {c.laddr.port} ;  pid : {proc.pid}')
                    print(proc)
                    return proc.pid
    return None

def kill_process_by_port(port):
    '''
    根据端口号杀进程及子进程
    '''
    pid = get_process_id_by_port(port)
    if pid:
        print(f'找到端口号为 {port} 的进程, 正在终止进程及子进程')
        kill_process(pid)
    else:
        print(f'未找到端口号为 {port} 的进程')


def stop_thread_by_tid(tid):
    """根据线程ID结束线程
    tid: 线程ID
    """
    exctype = SystemExit
    print(f"开始结束线程 {tid}")
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
        tid, ctypes.py_object(exctype))
    if res == 1:
        print("结束线程成功")
    elif res == 0:
        print("未找到线程id")
    else:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        print("PyThreadState_SetAsyncExc failed")                  
                        
if __name__=='__main__':

    kill_process_by_port(8190)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值