当我的长时间运行的程序开始时,我希望降低它的优先级,以便它不会消耗运行机器上的所有资源。情况使得必须限制该程序的使用。
有没有一种像 Python 命令这样的好方法,可以让该程序不利用其运行计算机的全部容量?
你可以通过运行nice pythonscript
来始终以“优先级”方式运行进程,
但如果你想在脚本中设置“优先级”,可以这样做:
import os
os.nice(20)
您可以逐步增加脚本运行的好感度,这样它在运行一段时间后就会利用越来越少的资源,只需将其集成到脚本中即可。
或者,在脚本外部运行后,您应该能够使用renice -p <pid>
。
psutil似乎是一个跨平台的解决方案,用于为Python设置进程优先级。
https://github.com/giampaolo/psutil
Windows特定的解决方案: http://code.activestate.com/recipes/496767/
def setpriority(pid=None,priority=1):
""" Set The Priority of a Windows Process. Priority is a value between 0-5 where
2 is normal priority. Default sets the priority of the current
python process but can take any valid process ID. """
import win32api,win32process,win32con
priorityclasses = [win32process.IDLE_PRIORITY_CLASS,
win32process.BELOW_NORMAL_PRIORITY_CLASS,
win32process.NORMAL_PRIORITY_CLASS,
win32process.ABOVE_NORMAL_PRIORITY_CLASS,
win32process.HIGH_PRIORITY_CLASS,
win32process.REALTIME_PRIORITY_CLASS]
if pid == None:
pid = win32api.GetCurrentProcessId()
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
win32process.SetPriorityClass(handle, priorityclasses[priority])
-20
到+20
的数字。普通用户能够nice操作,最高可提升20
级。特权用户可以进行nice降级,最低可调至-20
级。该命令是用于请求通过所选的值来调整nice级别,使用正数值表示nice(以使用更少的CPU),使用负数值表示降低nice级别。 - Anya Shenanigans