Python2 得到 CPU 和内存信息要怎么实现呢?

2015-08-31 17:49:36 +08:00
 Hakmor
2152 次点击
所在节点    问与答
3 条回复
askfermi
2015-08-31 17:57:04 +08:00
ls ('cat >/proc/cpuinfo')
ls ('cat >/proc/meminfo')
maemual
2015-08-31 17:58:08 +08:00
。。。。这个 Google 一下不就有了么。。
psutil
Hakmor
2015-08-31 20:32:52 +08:00
@askfermi
@maemual

谢谢。附上写好的代码。

```python
#!/usr/bin/env python
import time
import psutil

line_num = 1

def print_line (str ):
print str

#function of Get CPU State
def getCPUstate (interval=1 ):
return (" CPU: " + str (psutil.cpu_percent (interval )) + "%")

#function of Get Memory
def getMemorystate ():
phymem = psutil.phymem_usage ()
buffers = getattr (psutil, 'phymem_buffers', lambda: 0 )()
cached = getattr (psutil, 'cached_phymem', lambda: 0 )()
used = phymem.total - (phymem.free + buffers + cached )
line = " Memory: %6s" % (
str (int (used / 1024 / 1024 )) + "M",
)
return line

def poll (interval ):
"""Retrieve raw stats within an interval window."""
# sleep some time
time.sleep (interval )
# get cpu state
cpu_state = getCPUstate (interval )
# get memory
memory_state = getMemorystate ()
return (cpu_state,memory_state )

def refresh_window (cpu_state,memory_state ):
#print current time #cpu state #memory
print_line (time.asctime ())
print_line (cpu_state )
print_line (memory_state )

try:
interval =0
while 1:
args = poll (interval )
refresh_window (*args )
interval = 1
except (KeyboardInterrupt, SystemExit ):
pass
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/217372

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX