How can I read system information in Python on OS

2020-05-01 06:48发布

Following from this OS-agnostic question, specifically this response, similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from OS X using Python (including, but not limited to memory usage).

5条回答
甜甜的少女心
2楼-- · 2020-05-01 06:59

Here's a MacFUSE-based /proc fs:

http://www.osxbook.com/book/bonus/chapter11/procfs

If you have control of the boxes you're running your python program on it might be a reasonable solution. At any rate it's nice to have a /proc to look at!

查看更多
Animai°情兽
3楼-- · 2020-05-01 07:01

I did some more googling (looking for "OS X /proc") -- it looks like the sysctl command might be what you want, although I'm not sure if it will give you all the information you need. Here's the manpage: http://developer.apple.com/DOCUMENTATION/Darwin/Reference/ManPages/man8/sysctl.8.html

Also, wikipedia.

查看更多
Emotional °昔
4楼-- · 2020-05-01 07:15

You can get a large amount of system information from the command line utilities sysctl and vm_stat (as well as ps, as in this question.)

If you don't find a better way, you could always call these using subprocess.

查看更多
▲ chillily
5楼-- · 2020-05-01 07:20

The only stuff that's really nicely accesible is available from the platform module, but it's extremely limited (cpu, os version, architecture, etc). For cpu usage and uptime I think you will have to wrap the command line utilities 'uptime' and 'vm_stat'.

I built you one for vm_stat, the other one is up to you ;-)

import os, sys

def memoryUsage():

    result = dict()

    for l in [l.split(':') for l in os.popen('vm_stat').readlines()[1:8]]:
        result[l[0].strip(' "').replace(' ', '_').lower()] = int(l[1].strip('.\n '))

    return result

print memoryUsage()
查看更多
一纸荒年 Trace。
6楼-- · 2020-05-01 07:26

i was searching for this same thing, and i noticed there was no accepted answer for this question. in the intervening time since the question was originally asked, a python module called psutil was released:

https://github.com/giampaolo/psutil

for memory utilization, you can use the following:

>>> 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)
>>>

there are functions for cpu utilization, process management, disk, and network as well. the only omission from the module is a function for retrieving load average, but the python stdlib has os.getloadavg() if you are on a UNIX-like system.

psutil claims to support Linux, Windows, OSX, FreeBSD and Sun Solaris, but i have only tried OSX mavericks and fedora 20.

查看更多
登录 后发表回答