Use psutil to obtain system information in python
[Python] view plaincopyprint?
- #! /Usr/bin/envpython
- # Coding: UTF-8
- Importpsutil
- Importtime
- Importsys
- FromoptparseimportOptionParser
- Parser = OptionParser ()
- Parser. add_option ("-t", "-- time", dest = "time ",
- Help = "this parameter shows the bandwidth occupied by the current download.-t indicates the test time", metavar = "10 ")
- Parser. add_option ("-d", "-- deamon", action = "store_false", dest = "deamon", default = True,
- Help = "run this script in the background ")
- DefSysinfo ():
- Boot_Start = time. strftime ("% Y-% m-% d % H: % M: % S", time. localtime (psutil. boot_time ()))
- Time. sleep (0.5)
- Cpu_usage = psutil. cpu_percent ()
- RAM = int (psutil. virtual_memory (). total/(1027*1024 ))
- RAM_percent = psutil. virtual_memory (). percent
- Swap = int (psutil. swap_memory (). total/(1027*1024 ))
- Swap_percent = psutil. swap_memory (). percent
- Net_sent = psutil.net _ io_counters (). bytes_sent
- Net_recv = psutil.net _ io_counters (). bytes_recv
- Net_spkg = psutil.net _ io_counters (). packets_sent
- Net_rpkg = psutil.net _ io_counters (). packets_recv
- BFH = R' %'
- Print "\ 033 [1; 32 m boot time: % s \ 033 [1; m" % Boot_Start
- Print "\ 033 [1; 32 m current CPU usage: % s \ 033 [1; m" % (Cpu_usage, BFH)
- Print "\ 033 [1; 32 m physical memory: % dM \ t usage: % s \ 033 [1; m" % (RAM, RAM_percent, BFH)
- Print "\ 033 [1; 32mSwap memory: % dM \ t usage: % s \ 033 [1; m" % (Swap, Swap_percent, BFH)
- Print "\ 033 [1; 32 m sent: % dByte \ t sent packets: % d \ 033 [1; m" % (Net_sent, Net_spkg)
- Print "\ 033 [1; 32 m Received: % dByte \ t received packets: % d \ 033 [1; m" % (Net_recv, Net_rpkg)
- Foriinpsutil. disk_partitions ():
- Print "\ 033 [1; 32 m drive letter: % s mount point: % s usage: % s \ 033 [1; m" % (I [0], I [1], psutil. disk_usage (I [1]) [3], BFH)
- DefNet_io (s ):
- X = 0
- Sum = 0
- WhileTrue:
- Ifx> = s:
- Break
- R1 = psutil.net _ io_counters (). bytes_recv
- Time. sleep (1)
- R2 = psutil.net _ io_counters (). bytes_recv
- Y = r2-r1
- Print "%. 2fKb/s" % (y/1024.0)
- Sum + = y
- X + = 1
- Result = sum/x
- Print "\ 033 [1; average speed of 32 m % s: %. 2fKb/s \ 033 [1; m" % (x, result/1024.0)
- If _ name __= = "_ main __":
- (Options, args) = parser. parse_args ()
- Ifoptions. time:
- Net_io (int (options. time ))
- Else:
- Sysinfo ()
Running result:
Start Time: 08:39:45
Current CPU usage: 1.0%
Physical memory: 985 M usage: 26.5%
Swap memory: 2073 MB utilization: 0.0%
Sent: 140263274 Bytes Sent packets: 213610
Received: 1522552624 bytes received packets: 25313640
Drive letter:/dev/mapper/centos-root mount point:/usage: 32.8
Drive letter:/dev/xvda1 mount point:/boot usage: 19.2%
Systeminfo. py-t 10 usage:
1.18 Kb/s
0.98 Kb/s
1.11 Kb/s
0.94 Kb/s
0.89 Kb/s
0.92 Kb/s
1.29 Kb/s
1.24 Kb/s
1.21 Kb/s
0.73 Kb/s
Average speed within 10 seconds: 1.05 Kb/s