在跨平台的Python中更改进程优先级

Change process priority in Python, cross-platform

我有一个Python程序,它执行耗时的计算。 由于它使用较高的CPU,并且我希望系统保持响应状态,因此我希望程序将其优先级更改为低于正常值。

我找到了这个:
在Windows中设置进程优先级-ActiveState

但我正在寻找一种跨平台的解决方案。


这是我用来将进程设置为低于正常优先级的解决方案:

lowpriority.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def lowpriority():
   """ Set the priority of the process to below-normal."""

    import sys
    try:
        sys.getwindowsversion()
    except AttributeError:
        isWindows = False
    else:
        isWindows = True

    if isWindows:
        # Based on:
        #  "Recipe 496767: Set Process Priority In Windows" on ActiveState
        #   http://code.activestate.com/recipes/496767/
        import win32api,win32process,win32con

        pid = win32api.GetCurrentProcessId()
        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
        win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS)
    else:
        import os

        os.nice(1)

在Windows和Linux上的Python 2.6上进行了测试。


您可以使用psutil模块。

在POSIX平台上:

1
2
3
4
5
6
7
>>> import psutil, os
>>> p = psutil.Process(os.getpid())
>>> p.nice()
0
>>> p.nice(10)  # set
>>> p.nice()
10

在Windows上:

1
>>> p.nice(psutil.HIGH_PRIORITY_CLASS)


在每个类似Unix的平台(包括Linux和MacOsX)上,请参见os.nice

1
2
os.nice(increment)
Add increment to the process’s"niceness". Return the new niceness. Availability: Unix.

由于您已经拥有适用于大多数平台的Windows配方,因此在Windows以外的任何地方都可以使用正参数调用os.nice,在此处使用该配方。 没有"打包得很好"的跨平台解决方案AFAIK(很难打包这个组合,但是,仅打包就可以看到多少附加值?)


如果您无权访问其中一些模块,则可以在Windows中使用以下方法进行操作:

1
2
3
4
import os  
def lowpriority():  
   """ Set the priority of the process to below-normal."""  
    os.system("wmic process where processid=\""+str(os.getpid())+"\" CALL   setpriority \"below normal\"")

您显然可以像上面的示例一样区分OS类型,以实现兼容性。