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.

有帮助吗?

解决方案

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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top