Python - decrease niceness value Python - decrease niceness value unix unix

Python - decrease niceness value


Linux, by default, doesn't allow unprivileged users to decrease the nice value (i.e. increase the priority) of their processes, so that one user doesn't create a high-priority process to starve out other users. Python is simply forwarding the error the OS gives you as an exception.

The root user can increase the priority of processes, but running as root has other consequences.


This is not a restriction by Python or the os.nice interface. It is described in man 2 nice that only the superuser may decrease the niceness of a process:

nice() adds inc to the nice value for the calling process. (A higher nice value means a low priority.) Only the superuser may specify a negative increment, or priority increase. The range for nice values is described in getpriority(2).


I had the same Error [Errno 2] Operation not permitted.

I don't want to start my script with sudo so I came around with the following workaround:

def decrease_nice():    pid = os.getpid()    os.system("sudo renice -n -19 -p " + str(pid))def normal_nice():    pid = os.getpid()    os.system("sudo renice -n 0 -p " + str(pid))