在Python中更改进程优先级,跨平台
我有一个Python程序,它需要花很多时间来进行计算。因为这个程序会占用很多CPU资源,我希望我的系统能够保持响应,所以我想把这个程序的优先级设置为低一些。
我找到了这个链接:在Windows中设置进程优先级 - ActiveState
但是我想要一个可以在不同操作系统上都能用的解决方案。
5 个回答
11
在每个类Unix的平台上(包括Linux和MacOsX),可以查看os.nice
这里:
os.nice(increment)
Add increment to the process’s “niceness”. Return the new niceness. Availability: Unix.
因为你已经有了适用于Windows的解决方案,这样就覆盖了大部分平台——在除了Windows以外的地方都可以用正数作为参数调用os.nice,而在Windows上就用你已有的解决方案。就我所知,没有一个“打包好的”跨平台解决方案(把这些组合打包起来会很难,但你觉得单单打包它会带来多少额外的价值呢?)
29
你可以使用 psutil 这个模块。
在POSIX系统上:
>>> import psutil, os
>>> p = psutil.Process(os.getpid())
>>> p.nice()
0
>>> p.nice(10) # set
>>> p.nice()
10
在Windows系统上:
>>> p.nice(psutil.HIGH_PRIORITY_CLASS)
49
这是我用来把我的程序设置为低优先级的解决方案:
lowpriority.py
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测试过。