2009-06-21 338 views

回答

29

这是我用的解决方案我的过程设置为低于普通优先级:

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) 

测试上的Python 2.6在Windows和Linux。

+1

很好的解决方案,但你为什么叫而不是检查sys.platform sys.getwindowversion()? – 2011-09-05 13:59:57

+1

我只是想知道我是否在Windows上运行。 `sys.platform` [确实有记录返回值](http://docs.python.org/library/sys.html#sys.platform),但我不确定它是否值得信赖 - 是否真的返回` 64位Windows上的'win32'? (不管你信不信,我还没有64位Windows试用它!我想我现在应该可以在工作了) – 2011-09-05 22:58:11

9

在每一个类Unix平台(包括Linux和MacOSX的),看到os.nicehere

os.nice(increment) 
Add increment to the process’s “niceness”. Return the new niceness. Availability: Unix. 

既然你已经有一个Windows,涵盖大多数平台食谱 - 呼叫os.nice以积极的无处不在,但是在Windows中使用该配方。没有“很好的封装”的跨平台解决方案AFAIK(将很难打包这个组合,但是,你会看到多少额外的价值只是包装它?)

13

您可以使用psutil模块。

在POSIX平台:

>>> import psutil, os 
>>> p = psutil.Process(os.getpid()) 
>>> p.nice() 
0 
>>> p.nice(10) # set 
>>> p.nice() 
10 

在Windows上:

>>> p.nice(psutil.HIGH_PRIORITY_CLASS)