Change process priority in Python, cross-platform

后端 未结 4 1167
故里飘歌
故里飘歌 2020-11-29 20:39

I\'ve got a Python program that does time-consuming computations. Since it uses high CPU, and I want my system to remain responsive, I\'d like the program to change its prio

4条回答
  •  难免孤独
    2020-11-29 21:22

    Here's the solution I'm using to set my process to below-normal priority:

    lowpriority.py

    def lowpriority():
        """ Set the priority of the process to below-normal."""
    
        import sys
        try:
            sys.getwindowsversion()
        except AttributeError:
            isWindows = False
        else:
            isWindows = True
    
        if isWindows:
            # Based on:
            #   "Recipe 496767: Set Process Priority In Windows" on ActiveState
            #   http://code.activestate.com/recipes/496767/
            import win32api,win32process,win32con
    
            pid = win32api.GetCurrentProcessId()
            handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
            win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS)
        else:
            import os
    
            os.nice(1)
    

    Tested on Python 2.6 on Windows and Linux.

提交回复
热议问题