Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nicing a running python process?

Tags:

python

nice

When my longer-running programm starts, I want to lower its priority so it does not consume all resources avaiable on the machine it runs. Circumstances make it necessary that the programm limits itself.

Is there a nice-like python-command I could use so that the programm does not utilize the full capacity of the computer it is running on?

like image 563
AME Avatar asked Dec 18 '12 16:12

AME


2 Answers

you can always run the process with nice pythonscript,

but if you want to set the nice-level within the script you can do:

import os
os.nice(20)

You could progressively increment the nice level the longer the script is running, so it uses less and less resources over time, which is a simple matter of integrating it into the script.

Alternatively, from outside the script, once it's running you should be able to use renice -p <pid>

like image 104
Petesh Avatar answered Nov 04 '22 06:11

Petesh


psutil appears to be a cross platform solution to setting process priority for python.

https://github.com/giampaolo/psutil

The windows specific solution: 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])
like image 31
Louis Ricci Avatar answered Nov 04 '22 06:11

Louis Ricci