2009-08-18 6 views
10

파이썬에서 시스템 상태 (예 : 메모리 여유 공간, 실행중인 프로세스, CPU로드 등)를 얻을 수있는 방법이 있습니까? 나는 리눅스에서/proc 디렉토리에서 이것을 얻을 수 있다고 알고 있지만 유닉스와 윈도우에서도이 작업을하고 싶다. 나는 그것을위한 크로스 플랫폼 라이브러리는 아직 없다고 생각파이썬에서 시스템 상태 얻기

+2

중복 : http://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage- in-python http://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python/467291 –

답변

8

내가 그러한 라이브러리/패키지 모르겠어요 약간 더 파이썬 문서화 코드 끔찍한 문서화되지 않은 코드를 교체 현재 Linux와 Windows를 모두 지원합니다. libstatgrab은 매우 적극적으로 개발되지는 않았지만 (이미 다양한 유닉스 플랫폼을 지원함), AIX, Linux, SunOS 및 Darwin에서 작동하는 매우 활성 인 PSI (Python System Information)입니다. 두 프로젝트는 앞으로도 Windows 지원을 목표로합니다. 행운을 빕니다.

7

(가 분명하지만 하나 여야합니다) 내가 /proc/stat에서 현재 CPU의 부하를 가져 오는 데 사용 나는 그러나 하나 개의 조각을 제공 할 수 있습니다

리눅스 :

편집는 :

import time 

INTERVAL = 0.1 

def getTimeList(): 
    """ 
    Fetches a list of time units the cpu has spent in various modes 
    Detailed explanation at http://www.linuxhowtos.org/System/procstat.htm 
    """ 
    cpuStats = file("/proc/stat", "r").readline() 
    columns = cpuStats.replace("cpu", "").split(" ") 
    return map(int, filter(None, columns)) 

def deltaTime(interval): 
    """ 
    Returns the difference of the cpu statistics returned by getTimeList 
    that occurred in the given time delta 
    """ 
    timeList1 = getTimeList() 
    time.sleep(interval) 
    timeList2 = getTimeList() 
    return [(t2-t1) for t1, t2 in zip(timeList1, timeList2)] 

def getCpuLoad(): 
    """ 
    Returns the cpu load as a value from the interval [0.0, 1.0] 
    """ 
    dt = list(deltaTime(INTERVAL)) 
    idle_time = float(dt[3]) 
    total_time = sum(dt) 
    load = 1-(idle_time/total_time) 
    return load 


while True: 
    print "CPU usage=%.2f%%" % (getCpuLoad()*100.0) 
    time.sleep(0.1) 
+5

[os.getloadavg()] (http://docs.python.org /library/os.html#os.getloadavg) –