15

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?

AME
  • 2,499
  • 5
  • 29
  • 45

2 Answers2

26

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>

Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
  • 1
    With the normal caveat that unless running as `root` (or similar) you can't `nice` "down" – Jon Clements Dec 18 '12 at 16:46
  • 4
    Nice takes a number from `-20` to `+20`. An ordinary user nices up, to a maximum up-value of `20`. A privileged user can nice down, to a minimum down value of `-20`. The call is making a request to adjust the nice level by the value chosen, so to nice (and use less CPU), you use a positive value. To nice 'down', you use a negative value. – Anya Shenanigans Dec 19 '12 at 15:39
  • Does this effect subprocesses? – Basil Feb 14 '17 at 19:49
  • @Basil Yes. Including processes started by separate threads with the threading module. – SurpriseDog Jun 27 '22 at 01:44
7

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])
Giampaolo Rodolà
  • 12,488
  • 6
  • 68
  • 60
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62