Python 怎样获取当前计算机的 cpu,内存等信息
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 怎样获取当前计算机的 cpu,内存等信息相关的知识,希望对你有一定的参考价值。
用psutil包
cpu:
>>> import psutil>>> psutil.cpu_times()
scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, nice=0.0)
>>>
>>> for x in range(3):
... psutil.cpu_percent(interval=1)
...
4.0
5.9
3.8
>>>
>>> for x in range(3):
... psutil.cpu_percent(interval=1, percpu=True)
...
[4.0, 6.9, 3.7, 9.2]
[7.0, 8.5, 2.4, 2.1]
[1.2, 9.0, 9.9, 7.2]
>>>
>>>
>>> for x in range(3):
... psutil.cpu_times_percent(interval=1, percpu=False)
...
scputimes(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
scputimes(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
scputimes(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
>>>
>>> psutil.cpu_count()
4
>>> psutil.cpu_count(logical=False)
2
>>>
内存:
>>> psutil.virtual_memory()svmem(total=8374149120L, available=2081050624L, percent=75.1, used=8074080256L, free=300068864L, active=3294920704, inactive=1361616896, buffers=529895424L, cached=1251086336)
>>> psutil.swap_memory()
sswap(total=2097147904L, used=296128512L, free=1801019392L, percent=14.1, sin=304193536, sout=677842944)
>>> 参考技术A 用psutil包
cpu:
12345678910111213141516171819202122232425262728293031>>> import psutil>>> psutil.cpu_times()scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, nice=0.0)>>>>>> for x in range(3):... psutil.cpu_percent(interval=1)...4.05.93.8>>>>>> for x in range(3):... psutil.cpu_percent(interval=1, percpu=True)...[4.0, 6.9, 3.7, 9.2][7.0, 8.5, 2.4, 2.1][1.2, 9.0, 9.9, 7.2]>>>>>>>>> for x in range(3):... psutil.cpu_times_percent(interval=1, percpu=False)...scputimes(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)scputimes(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)scputimes(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)>>>>>> psutil.cpu_count()4>>> psutil.cpu_count(logical=False)2>>>
内存:
12345>>> psutil.virtual_memory()svmem(total=8374149120L, available=2081050624L, percent=75.1, used=8074080256L, free=300068864L, active=3294920704, inactive=1361616896, buffers=529895424L, cached=1251086336)>>> psutil.swap_memory()sswap(total=2097147904L, used=296128512L, free=1801019392L, percent=14.1, sin=304193536, sout=677842944)>>> 参考技术B 如果想自己写程序来实现,可以参考它们的源码。
top/free都是在procps包中(apt-get source procps)。
找到cpus_refresh()函数,可以看到它是怎样从/proc/stat解析出CPU的使用率的。
meminfo()函数则展示了如何从/proc/meminfo解析出内存的使用率(这个文件自己解析也很简单)。本回答被提问者采纳
以上是关于Python 怎样获取当前计算机的 cpu,内存等信息的主要内容,如果未能解决你的问题,请参考以下文章