Hi,

I need to change the nice value of a process, but not sure how to do it.
My process has a priority of 0 when it is launched , i need to decrease it to some +ve value.

I know we use

os.system("renice -n value -p pidof process").

to change, but not sure whether to change the value before launching the process or after launching the process.

Any help is very much appreciated.

Thanks,

Dani AI

Generated

Short answer for : you can do either, but the usual advice is to set the niceness inside the child right before exec if you want the new process to start with the requested niceness (avoids race with a separate renice), or change it after launch if the process already exists. The standard-library calls you need are documented in Python’s os module and subprocess module. (os — Python stdlib) (subprocess — Python stdlib). (docs.python.org)

Example (POSIX): run a tiny initializer in the child that sets the priority before exec. This avoids the “start the process then renice it” race. Use preexec_fn with os.setpriority (POSIX) or os.nice to adjust the calling process’s niceness in the child:

import os
import subprocess

def _child_init():
    # set absolute priority to +10 (higher niceness = lower scheduling priority)
    os.setpriority(os.PRIO_PROCESS, 0, 10)

p = subprocess.Popen(['/path/to/program', 'arg1'], preexec_fn=_child_init)

Note: preexec_fn is POSIX-only and is unsafe in multi-threaded parents; keep the function trivial. (docs.python.org)

To change an already-running process from Python use os.setpriority (or have the target process call os.nice on itself). Example:

import os
pid = 12345
os.setpriority(os.PRIO_PROCESS, pid, 12)   # set pid's nice to 12

Reminder: niceness values range roughly -20 (highest priority) to +19 (lowest); unprivileged users may only increase niceness (make processes "nicer" / lower priority); lowering niceness (negative values) requires privileges. See the nice/renice and setpriority docs for platform details. (man7.org)

If you need cross-platform convenience or a higher-level API (Windows priority classes, etc.) the third‑party route mentioned earlier by is worth considering; otherwise the snippets above use only the standard library.

Recommended Answers

All 3 Replies

If you don't mind using a third party library, you may consider psutil where process objects have get_nice() and set_nice() methods.

I am not that lucky..., i cannot use that , i mean its better if we can do it by existing standard calls

I don't see how the process could have a pid before you launch it, so the answer is most certainly after launching the process. You could also start the program directly with the nice command.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.