python模块之psutil

psutil安装

安装方法网上很多种,这里不在叙述:介绍一种pip install psutil

获取系统基本信息

psutil使用

>>> import psutil
>>> dir(psutil)  #python dir()函数,获取当前模块的属性列表[dir函数](http://www.runoob.com/python/python-func-dir.html)
['AF_LINK', 'AIX', 'AccessDenied', 'BSD', 'CONN_CLOSE', 'CONN_CLOSE_WAIT', 
'CONN_CLOSING', 'CONN_ESTABLISHED', 'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 
'CONN_LAST_ACK', 'CONN_LISTEN', 'CONN_NONE', 'CONN_SYN_RECV', 
'CONN_SYN_SENT', 'CONN_TIME_WAIT', 'Error', 'FREEBSD', 'IOPRIO_CLASS_BE', 
'IOPRIO_CLASS_IDLE', 'IOPRIO_CLASS_NONE', 'IOPRIO_CLASS_RT', 'LINUX', 
'NETBSD', 'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN', 
'NoSuchProcess', 'OPENBSD', 'OSX', 'POSIX', 'POWER_TIME_UNKNOWN', 
'POWER_TIME_UNLIMITED', 'PROCFS_PATH', 'Popen', 'Process', 'RLIMIT_AS', 
'RLIMIT_CORE', 'RLIMIT_CPU', 'RLIMIT_DATA', 'RLIMIT_FSIZE', 
'RLIMIT_LOCKS', 'RLIMIT_MEMLOCK', 'RLIMIT_MSGQUEUE', 'RLIMIT_NICE', 
'RLIMIT_NOFILE', 'RLIMIT_NPROC', 'RLIMIT_RSS', 'RLIMIT_RTPRIO', 
'RLIMIT_RTTIME', 'RLIMIT_SIGPENDING', 'RLIMIT_STACK', 'RLIM_INFINITY', 
'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED', 
'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 
'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKING', 'STATUS_ZOMBIE', 
'SUNOS', 'TimeoutExpired', 'WINDOWS', 'ZombieProcess', '_PY3', 
'_TOTAL_PHYMEM', '__all__', '__author__', '__builtins__', '__doc__', 
'__file__', '__name__', '__package__', '__path__', '__version__', 
'_as_dict_attrnames', '_assert_pid_not_reused', '_common', '_compat', 
'_cpu_busy_time', '_cpu_times_deltas', '_cpu_tot_time', '_exceptions', 
'_last_cpu_times', '_last_cpu_times_2', '_last_per_cpu_times', 
'_last_per_cpu_times_2', '_pmap', '_ppid_map', '_pprint_secs', '_pslinux',
 '_psplatform', '_psposix', '_psutil_linux', '_psutil_posix', '_timer', 
'cpu_percent', 'cpu_stats', 'cpu_times', 'cpu_times_percent', 'datetime',
 'disk_io_counters', 'disk_partitions', 'disk_usage', 'errno', 
'net_io_counters', 'os', 'pid_exists', 'pids', 'process_iter', 'pwd', 
'sensors_battery', 'sensors_fans', 'sensors_temperatures', 'signal', 
'subprocess', 'swap_memory', 'sys', 'test', 'time', 'traceback', 'users', 
'version_info', 'virtual_memory', 'wait_procs']

python psutil概要

psutil 模块主要用于系统性能监控,分析和限制管理资源及进程的管理,实现了同等命令工具提供的功能、
比如:

[ps, top, lsof, netstat, ifconfig, who, df, kill, free, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap]
###psutil例子
####1. CPU信息
psutil.cpu_count(logical=False) cpu物理个数
psutil.cpu_percent() CPU使用百分比
psutil.cpu_times()
psutil.cpu_times_percent(interval=1, percpu=True/False)

####2. mem信息
psutil.swap_memory()
psutil.virtual_memory()

>>> psutil.virtual_memory()
svmem(total=1929351168, available=1400414208, percent=27.4, used=369942528, free=551243776, active=484835328, inactive=703434752, buffers=0, cached=1008164864, shared=2277376)
>>> psutil.swap_memory()
sswap(total=1719660544, used=285163520, free=1434497024, percent=16.6, sin=536428544, sout=759148544)

####3. 磁盘信息
psutil.disk_io_counters()
psutil.disk_usage('/')
psutil.disk_partitions()

>>> psutil.disk_io_counters()
sdiskio(read_count=2248425, write_count=3823798, read_bytes=74719505408, write_bytes=346022062080, read_time=36343167, write_time=2315765377, read_merged_count=112706, write_merged_count=1563457, busy_time=26451323)
>>> psutil.disk_usage('/')
sdiskusage(total=29949427712, used=21998997504, free=7950430208, percent=73.5)
>>> psutil.disk_partitions()
[sdiskpart(device='/dev/mapper/centos-root', mountpoint='/', fstype='xfs', opts='rw,seclabel,relatime,attr2,inode64,noquota'), sdiskpart(device='/dev/sda1', mountpoint='/boot', fstype='xfs', opts='rw,seclabel,relatime,attr2,inode64,noquota')]

####4. 网络和网卡信息
psutil.net_connections()
pstuil.net_if_addrs()
psutil.net_if_stats()
psutil.net_io_counters()

>>> psutil.net_if_addrs()
{'lo': [snic(family=2, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None), snic(family=10, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None), snic(family=17, address='00:00:00:00:00:00', netmask=None, broadcast=None, ptp=None)], 'eno16777984': [snic(family=2, address='10.1.100.104', netmask='255.255.255.0', broadcast='10.1.100.255', ptp=None), snic(family=10, address='fe80::250:56ff:feab:bb18%eno16777984', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), snic(family=17, address='00:50:56:ab:bb:18', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
>>> psutil.net_if_stats()
{'lo': snicstats(isup=True, duplex=0, speed=0, mtu=65536), 'eno16777984': snicstats(isup=True, duplex=2, speed=10000, mtu=1500)}
>>> psutil.net_io_counters()
snetio(bytes_sent=17689863602, bytes_recv=23961220626, packets_sent=9518552, packets_recv=27992275, errin=0, errout=0, dropin=211, dropout=0)

####5. 用户登录,开机时间
psutil.boot_time()
psutil.users()

>>> psutil.boot_time()
1526280877.0
>>> psutil.users()
[suser(name='root', terminal='pts/0', host='root', started=1527053312.0, pid=43013), suser(name='root', terminal='pts/3', host='root', started=1527043584.0, pid=40485), suser(name='root', terminal='pts/4', host='root', started=1527057792.0, pid=45406), suser(name='root', terminal='pts/5', host='root', started=1527050112.0, pid=42086), suser(name='root', terminal='pts/6', host='root', started=1527065216.0, pid=46673)]

####6. Process
>>> #导入模块,失败的说明安装失败
>>> import psutil
>>> #列出当前所有进程的pid,返回一个list
>>> psutil.pids()
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, ...]
>>> #实例化一个Process对象,指定某个进程pid
>>> p=psutil.Process(10405)
>>> #进程名称
>>> p.name()
'java'
>>> #进程pid
>>> p.pid
10405
>>> #父进程pid
>>> p.ppid()
10403
>>> #返回父进程,如果不存在父进程,则返回None。
>>> p.parent()
<psutil.Process(pid=10403, name='javatest.sh') at 30842192>
>>> #进程bin路径
>>> p.exe()
'/usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java'
>>> #进程工作目录绝对路径
>>> p.cwd()
'/home/sijitao.net/javatest'
>>> #返回哪个用户运行的进程
>>> p.username()
'sijitao.net'
>>> #进程状态
>>> p.status()
'sleeping'
>>> #进程创建时间,时间戳格式
>>> p.create_time()
1441074440.74
>>> #改成常规时间格式
>>> import datetime
>>> datetime.datetime.fromtimestamp(p.create_time())
datetime.datetime(2015, 9, 1, 10, 27, 20, 740000)
>>> print datetime.datetime.fromtimestamp(p.create_time())
2015-09-01 10:27:20.740000
>>> datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d %H:%M:%S")
'2015-09-01 10:27:20'
>>> #进程uid信息
>>> p.uids()
puids(real=1003, effective=1003, saved=1003)
>>> #进程gid信息
>>> p.gids()
pgids(real=1002, effective=1002, saved=1002)
>>> #进程cpu时间信息,包括user和system两个时间。
>>> p.cpu_times()
pcputimes(user=17914.4, system=1444.41)
>>> #进程占用内存利用率百分比
>>> p.memory_percent()
25.29625956853707
>>> #进程内存使用的详细信息
>>> p.memory_info() 
pmem(rss=2117931008, vms=6930079744)
>>> #a为进程使用的实际内存rss,b为使用的虚拟内存vms
>>> a, b = p.memory_info()
>>> print "a=%s,b=%s" % (a,b)
a=2104492032,b=6930079744
>>> #进程的io信息,包括读写io数和字节数
>>> p.io_counters()
pio(read_count=1028798665, write_count=1448643, read_bytes=278528, write_bytes=31179665408)
>>> #进程开启的线程数
>>> p.num_threads()
74
>>> #返回打开进程socket的namedutples列表,包括fs,family,laddr等信息
>>> p.connections()
[pconn(fd=178, family=10, type=1, laddr=('::ffff:xxx.xxx.xxx.xxx', 41154), raddr=('::ffff:xxx.xxx.xxx.xxx', 80), status='CLOSE_WAIT'), pconn(......]


####7. Popen
psutil有一个Popen类,可以获取用户启动的应用进程信息,还可以跟踪程序进程的状态

>>> from subprocess import PIPE
>>> p1=psutil.Popen(["/usr/bin/python","-c","print('hello')"],stdout=PIPE)
>>> p1.name()
'python'
>>> p1.username()
'root'
>>> p1.communicate()
('hello\n', None)
>>> p1.cpu_times()
pcputimes(user=0.01, system=0.01)

参考链接:
1. http://blog.nbhao.org/2046.html
2. https://blog.csdn.net/killvoon/article/details/49425925

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值