2012-12-18 34 views
8

當我跑步的時間延長,PROGRAMM開始,我想降低其優先級,以便它不會消耗它運行在機器上繳費的所有資源。情況使得程序必須自我限制。Nicing正在運行的Python進程?

是否有一個很好的樣Python的命令,我可以使用,這樣程序不使用它正在運行的計算機的全部容量?

回答

16

你總是可以運行與nice pythonscript過程中,

,但如果你想設置的腳本中可有可無的水平,你可以這樣做:

import os 
os.nice(20) 

你可以逐步遞增好的水平的時間越長腳本運行,所以隨着時間的推移使用越來越少的資源,這是其集成到腳本的一個簡單的事情。

另外,從腳本之外,一旦它的運行,你應該能夠使用renice -p <pid>

+0

隨着正常告誡說,除非是作爲'root'(或類似)運行,就不能'nice' 「向下」 –

+0

是什麼下注的語義? – AME

+2

尼斯需要從'-20'一個數字'+ 20'。普通用戶會注意到最大值爲20。特權用戶可以很好地下降,最低值爲'-20'。呼叫正在請求調整由所選擇的價值不錯的水平,所以要很好的(和使用較少的CPU),您使用的是正值。爲了不錯,請使用負值。 – Petesh

4

psutil似乎是一個跨平臺的解決方案,爲蟒蛇設置進程的優先級。

https://github.com/giampaolo/psutil

窗戶具體的解決方案:http://code.activestate.com/recipes/496767/

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]) 
+1

方便的Windows - 但除非'nice'是一個通用術語,我認爲它是基於* nix的 –