在 Python 中更改进程优先级,跨平台 [英] Change process priority in Python, cross-platform
本文介绍了在 Python 中更改进程优先级,跨平台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个执行耗时计算的 Python 程序.由于它使用高 CPU,并且我希望我的系统保持响应,我希望程序将其优先级更改为低于正常.
I've got a Python program that does time-consuming computations. Since it uses high CPU, and I want my system to remain responsive, I'd like the program to change its priority to below-normal.
我发现了这个:在 Windows 中设置进程优先级 - ActiveState
但我正在寻找跨平台的解决方案.
But I'm looking for a cross-platform solution.
推荐答案
这是我用来将我的进程设置为低于正常优先级的解决方案:
Here's the solution I'm using to set my process to below-normal priority:
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 上测试.
Tested on Python 2.6 on Windows and Linux.
这篇关于在 Python 中更改进程优先级,跨平台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文