What is the os.nice() method in Python?

This os.nice() method is used to add increments in the process's niceness Nice valueand return an updated niceness value. The nice value or niceness is used to invoke utility to assign CPU time to a process.

It ranges between -20 to +19, inclusive of boundary values. The higher the nice value, the lesser the priority and CPU time, and vice versa.

Note: Root or Superuser has privileges to change process niceness.

Syntax


os.nice(increment)

Parameters

It takes the following argument value.

increment: This is an integer value between -20 and +19, where -20 is the maximum and +19 is the minimum. It is calculated in different ways depending upon system architecture. In UNIX based systems, it is calculated as: new_niceness = old_niceness + specified_value.

Return value

It returns process niceness or nice value as an integer.

Explanation

In this code snippet, we'll use the os.nice() method and its different variants.

# importing os and random module
import os
import random
# current nice value of the process
# set to random value
niceness = os.nice(random.randint(1,20))
# show current niceness value
print("Current niceness value:", niceness)
# set to default niceness
niceness = os.nice(0)
# show current niceness value
print("Current niceness value:", niceness)
Calling the os.nice() function
  • Line 6–8: We call os.nice() with a random argument value between 1 and 20. In line 8, we print the updated value to the console.
  • Line 10–12: We call os.nice() at 0, which is also considered a default value. In line 12, we print the updated value to the console.

Free Resources