Python进程管理

来自CloudWiki
跳转至: 导航搜索

安装包

pip3 install psutil

获取进程信息

获取所有进程的id

>>> import psutil
>>> for pid in psutil.pids():
	print(pid,end=',')

0,4,76,96,472,544,580,584,604,620,636,748,756,848,892,900,940,1028,1096,1152,1220,1300,1388,1480,1488,1504,1516,1548,1552,1612,1616,1644,1712,1744,1800,1916,1928,1944,1984,2028,2060,2164,2280,2288,2296,2340,2348,2404,2408,2444,2456,2476,2484,2524,2652,2664,2672,2760,2928,2944,2960,3244,3348,3372,3388,3...

练习:统计现在系统中的总进程数

查找特定进程的信息

  1. 查找qq程序的有关信息:
>>> for proc in psutil.process_iter(attrs=['pid','name','username']):
	if proc.info['name'].startswith('QQ'):
		print(proc.info)

{'pid': 3976, 'name': 'QQProtect.exe', 'username': None} {'pid': 11444, 'name': 'QQLiveService.exe', 'username': 'DESKTOP-LN2H42N\\thinkpad'} {'pid': 47496, 'name': 'QQ.exe', 'username': 'DESKTOP-LN2H42N\\thinkpad'} {'pid': 69388, 'name': 'QQExternal.exe', 'username': 'DESKTOP-LN2H42N\\thinkpad'}</nowiki>

前面使用psutil.process_iter获取了进程相关的信息,返回结果是一个可迭代对象,每个元素的info是一个字典,通过字典可以获取我们关心的信息。

思考:如何获得获得每个元素 info的pid,name,username?

练习:查询进程函数

#show_process()
def find_procs_by_name(name):
    "Return a list of processes matching 'name'."
    ls = []
    for proc in psutil.process_iter(attrs=['pid','name','username']):
        if name in proc.info['name']:
            #print(proc.info)
            ls.append(proc)

    return ls

ls=find_procs_by_name("firefox")
print(ls)

查询进程的资源占用

获取进程的其他信息 还可以通过以下方式:

In [18]: psutil.Process(10848).cpu_times()#获取cpu占用
Out[18]: pcputimes(user=1103.40625, system=462.203125, children_user=0.0, children_system=0.0)

In [19]: psutil.Process(10848).memory_info()#获取内存占用,rss就是实际占用的内存
Out[19]: pmem(rss=403660800, vms=533426176, num_page_faults=22055661, peak_wset=541741056, wset=403660800, peak_paged_pool=1336168, paged_pool=1140336, peak_nonpaged_pool=363148, nonpaged_pool=234576, pagefile=533426176, peak_pagefile=563355648, private=533426176)

In [20]: psutil.Process(10848).num_threads()#获取线程数
Out[20]: 96

In [21]: psutil.Process(10848).memory_percent()#获取内存占比
Out[21]: 2.233989187849646

例题:自制“任务管理器”

import psutil

def show_process():
    print("pid","name","cpu_percent","mem_percent")
    for pid in psutil.pids():
            pro = psutil.Process(pid)
            p_name = pro.name()
            p_cpud = pro.cpu_percent(interval=1)
            p_mem = round(pro.memory_percent(),2)
            print(pid,"\t",p_name,"\t",p_cpud,"\t",p_mem)


show_process()

练习:任务管理器,电脑中哪一个最占内存资源,哪一个最占CPU ?

https://www.jianshu.com/p/d9a3372cc04d

杀死进程

(本操作需要以管理员权限运行IDLE 或python IDE)

p = psutil.Process(1689)

p.terminate()

例题:结束QQ进程

def get_procs_by_name(name):
    "Return a list of processes matching 'name'."
    ls = []
    for proc in psutil.process_iter(attrs=['pid','name','username']):
        if name in proc.info['name']:
            #print(proc.info)
            ls.append(proc.pid)

    return ls

def kill_procs_by_id(ls):
    for pid in ls:
        p = psutil.Process(pid)
        p.terminate()
        print("Process",pid,"terminated")
        
ls=get_procs_by_name("QQ")
kill_procs_by_id(ls)


杀掉子进程

import psutil

def reap_children(timeout=3):
    "Tries hard to terminate and ultimately kill all the children of this process."
    def on_terminate(proc):
        print("process {} terminated with exit code {}".format(proc, proc.returncode))

    procs = psutil.Process().children()
    # send SIGTERM
    for p in procs:
        p.terminate()
    gone, alive = psutil.wait_procs(procs, timeout=timeout, callback=on_terminate)
    if alive:
        # send SIGKILL
        for p in alive:
            print("process {} survived SIGTERM; trying SIGKILL" % p)
            p.kill()
        gone, alive = psutil.wait_procs(alive, timeout=timeout, callback=on_terminate)
        if alive:
            # give up
            for p in alive:
                print("process {} survived SIGKILL; giving up" % p)