我有一个Python程序,进行耗时的计算。由于它使用高CPU,并且我希望我的系统保持响应,请将程序的优先级更改为低于正常优先级。
我找到了这个: 在Windows中设置进程优先级-ActiveState
但是我正在寻找跨平台的解决方案。
我有一个Python程序,进行耗时的计算。由于它使用高CPU,并且我希望我的系统保持响应,请将程序的优先级更改为低于正常优先级。
我找到了这个: 在Windows中设置进程优先级-ActiveState
但是我正在寻找跨平台的解决方案。
这是我用来将进程设置为低于正常优先级的解决方案:
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。
>>> 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)
10
与psutil.HIGH_PRIORITY_CLASS
)。“跨平台”应该意味着“在所有平台上使用相同的API”。我认为这是很遗憾的。 - Craig McQueen在每个类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函数,在那里使用该配方。据我所知,没有“好包装”的跨平台解决方案(将这个组合打包起来可能很困难,但是,如果只打包它,您会看到多少额外价值?-)
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\"")
这里有一段对我来说很好的代码:
import sys
import os
import psutil
os_used = sys.platform
process = psutil.Process(os.getpid()) # Set highest priority for the python script for the CPU
if os_used == "win32": # Windows (either 32-bit or 64-bit)
process.nice(psutil.REALTIME_PRIORITY_CLASS)
elif os_used == "linux": # linux
process.nice(psutil.IOPRIO_HIGH)
else: # MAC OS X or other
process.nice(20)
如需了解代码中使用的数字和常量的更多信息,请参阅完整文档:
https://psutil.readthedocs.io/en/latest/#
sys.platform
有文档记录的返回值,但我不确定它是否可信--它是否真的在64位Windows上返回“win32”?(信不信由你,我还没有尝试在64位Windows上运行!我想现在应该可以在工作中尝试一下) - Craig McQueensys.platform
确实返回'win32'
。 - Jonathan Livnisys.platform
返回“win32”。 - Molombywin32process.SetPriorityClass(win32api.GetCurrentProcess(), win32process.HIGH_PRIORITY_CLASS)
呢? - panda-34