python下通过wmic设置程序的优先级~~~

发布于:2025-05-25 ⋅ 阅读:(23) ⋅ 点赞:(0)

在开发过程中,经常会碰到需要设置程序优先级,这时候可以手动到任务管理器中调整,但是这多多少少有些不方便,那么这时候我们就可以通过subprocess调用wmic命令来实现,方法如下:

step 1 必要的引用:

import subprocess                           # Subprocess calling

step 2 函数封装:

def set_priority_by_name(process_name, priority="normal"):

    priority_map = {
        "realtime": 256,         # REALTIME_PRIORITY_CLASS(实时)
        "high": 128,             # HIGH_PRIORITY_CLASS(高)
        "above_normal": 32768,   # ABOVE_NORMAL_PRIORITY_CLASS(高于正常)
        "normal": 32,            # NORMAL_PRIORITY_CLASS(正常)
        "below_normal": 16384,   # BELOW_NORMAL_PRIORITY_CLASS(低于正常)
        "low": 64,               # IDLE_PRIORITY_CLASS(低)
    }

    # 获取优先级数值(默认正常)
    priority_value = priority_map.get(priority.lower(), 32)

    # 构造 wmic 命令
    cmd = f'wmic process where name="{process_name}" call setpriority {priority_value}'

    try:  # 需要管理员权限(尤其是 high/realtime)
        subprocess.run(cmd, check=True, shell=True, capture_output=True)
    except subprocess.CalledProcessError as e:
        print(f"speed level set failed: {e.stderr.decode().strip()}")
    except Exception as e:
        print(f"unknown error: {str(e)}")
    else:
        print(f"set {process_name}'s priority to: {priority}")
    #end tray

#end def

step3. 调用 

set_priority_by_name("yourapp1.exe", "above_normal")    # 设为above_normal
set_priority_by_name("yourapp2.exe", "high")            # 设为high


网站公告

今日签到

点亮在社区的每一天
去签到