当我的运行时间较长的程序启动时,我想降低它的优先级,这样它就不会消耗它运行的机器上的所有可用资源。环境使程序有必要限制自己。
有没有我可以使用的类似 python 的命令,这样程序就不会利用它正在运行的计算机的全部容量?
您始终可以使用nice pythonscript
,
但是如果你想在脚本中设置 nice-level,你可以这样做:
import os
os.nice(20)
脚本运行的时间越长,您可以逐步增加 nice 级别,因此随着时间的推移,它使用的资源越来越少,这很简单,只需将其集成到脚本中即可。
或者,从脚本外部,一旦它运行,您应该能够使用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])