Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change process priority in Python, cross-platform

Tags:

python

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.

I found this: Set Process Priority In Windows - ActiveState

But I'm looking for a cross-platform solution.

like image 839
Craig McQueen Avatar asked Jun 21 '09 02:06

Craig McQueen


People also ask

How do you set priority in Python?

Using heapqThe heapq module in Python can be used to implement Priority Queue. In this code, a heap is created and the elements (priority key, value) are pushed into the heap. The heapq module implements min-heap by default. The element with the smallest key is considered to have the highest priority in min-heap.

Which process has the highest priority?

A process' priority can range between 0 (lowest priority) and 127 (highest priority). User mode processes run at lower priorities (lower values) than system mode processes. A user mode process can have a priority of 0 to 65, whereas a system mode process has a priority of 66 to 95.


2 Answers

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) 

Tested on Python 2.6 on Windows and Linux.

like image 65
Craig McQueen Avatar answered Sep 18 '22 09:09

Craig McQueen


You can use psutil module.

On POSIX platforms:

>>> import psutil, os >>> p = psutil.Process(os.getpid()) >>> p.nice() 0 >>> p.nice(10)  # set >>> p.nice() 10 

On Windows:

>>> p.nice(psutil.HIGH_PRIORITY_CLASS) 
like image 32
Giampaolo Rodolà Avatar answered Sep 17 '22 09:09

Giampaolo Rodolà