pythonlinuxschedulingnice

Is there a way to "nice" a method of a Python script


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.


Solution

  • 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.