Welcome, guest | Sign In | My Account | Store | Cart

This function allows you to set process priority under windows. It defaults to setting the priority of the current python process but can set anything for which you have a process ID. I find it handy to set a long-running job with lower than normal priority so the computer doesn't feel sluggish while it runs.

Python, 17 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def setpriority(pid=None,priority=1):
    """ Set The Priority of a Windows Process.  Priority is a value between 0-5 where
        2 is normal priority.  Default sets the priority of the current
        python process but can take any valid process ID. """
        
    import win32api,win32process,win32con
    
    priorityclasses = [win32process.IDLE_PRIORITY_CLASS,
                       win32process.BELOW_NORMAL_PRIORITY_CLASS,
                       win32process.NORMAL_PRIORITY_CLASS,
                       win32process.ABOVE_NORMAL_PRIORITY_CLASS,
                       win32process.HIGH_PRIORITY_CLASS,
                       win32process.REALTIME_PRIORITY_CLASS]
    if pid == None:
        pid = win32api.GetCurrentProcessId()
    handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
    win32process.SetPriorityClass(handle, priorityclasses[priority])

4 comments

Milan Pipersky 13 years, 10 months ago  # | flag

Good help for this Python newbie: easy to find with a Google search, and it worked as is. Thanks!

Giampaolo RodolĂ  11 years, 9 months ago  # | flag

You can also use psutil [1], which is cross platform:

>>> import psutil, os
>>> p = psutil.Process(os.getpid())
>>> p.set_nice(psutil.HIGH_PRIORITY_CLASS)

[1] http://code.google.com/p/psutil/

Garrett 11 years, 6 months ago  # | flag

I've used this several times. It is fantastic code.

Nitin Kumar 11 years, 3 months ago  # | flag

How to change the priority of process running in System user mode? For System user mode process above code gives "AccessDenied"