4

My scripts have multiple components, and only some pieces need to be nice-d. i.e., run in low priority.

Is there a way to nice only one method of Python, or I need to break it down into several processes?

I am using Linux, if that matters.

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
CuriousMind
  • 15,168
  • 20
  • 82
  • 120
  • 1
    Process priority is managed by the OS, so I'm pretty sure you'd either have to use `subprocess` or do some sort of system where your script finds its own process and changes its priority dynamically. Of course, the better question to ask is if any parts really need to run at high priority, or you could just run the whole thing at low priority. – Silas Ray Jan 26 '13 at 04:19

1 Answers1

7

You could write a decorator that renices the running process on entry and exit:

import os
import functools

def low_priority(f):
    @functools.wraps(f)
    def reniced(*args, **kwargs):
        os.nice(5)
        try:
            f(*args,**kwargs)
        finally:
            os.nice(-5)
    return reniced

Then you can use it this way:

@low_priority
def test():
    pass # Or whatever you want to do.

Disclaimers:

  1. Works on my machine, not sure how universal os.nice is.
  2. As noted below, whether it works or not may depend on your os/distribution, or on being root.
  3. Nice is on a per-process basis. Behaviour with multiple threads per process will likely not be sane, and may crash.
Christophe Biocca
  • 3,388
  • 1
  • 23
  • 24