Hello everyone , I'm brother Chen ~

Today, I'd like to introduce a library that can obtain the current system information ——psutil

utilize psutil Library can get some information about the system , Such as cpu, Memory usage, etc , This allows you to view the current system usage , Collecting these information in real time can achieve the purpose of real-time monitoring system .

psutil library

psutil It's easy to install

pip install psutil

psutil What system information can the library get ?

psutil What are the functions 
1. Memory usage
2. Disk usage
3.cpu Usage rate
4. The network interface sends and receives traffic
5. Get the current network speed
6. The current process of the system

The following is a demonstration through a specific code case

Memory usage

import psutil
# Memory
mem = psutil.virtual_memory()
# Total system memory
zj = float(mem.total) / 1024 / 1024 / 1024
# The system has used memory
ysy = float(mem.used) / 1024 / 1024 / 1024
# System free memory
kx = float(mem.free) / 1024 / 1024 / 1024
print(' Total system memory :%d.4GB' % zj)
print(' The system has used memory :%d.4GB' % ysy)
print(' System free memory :%d.4GB' % kx)

Gets the total memory of the current system , Used memory , And free memory

The unit of memory obtained here is bytes , So you need to divide by 1024 To G, The same is true below, so I won't repeat the explanation .

Get the system cpu Information

# Show cpu All logical information 
# see cpu Information of logical number
print(u" Logic CPU Number : %s" % psutil.cpu_count())
# see cpu Information about the number of Physics
print(u" Physics CPU Number : %s" % psutil.cpu_count(logical=False))
#CPU The usage rate of
cpu = (str(psutil.cpu_percent(1))) + '%'
print(u"cup Usage rate : %s" % cpu)

obtain cpu Information , And this machine cpu Number ( Including logic cpu Numbers and physics cpu Count ), Current cpu Usage rate ( every other 1 Seconds to get once , Get and view real-time cpu Usage )

System disk usage

part = psutil.disk_partitions()
for i in part:
dk = psutil.disk_usage('/')
# Total disk
total = dk.total / 1024 / 1024 / 1024
used = dk.used / 1024 / 1024 / 1024
free = dk.free / 1024 / 1024 / 1024
print(' Total system disks :%d.3GB' % total)
print(' The system is already using disk :%d.3GB' % used)
print(' System free disk :%d.3GB' % free)
print(u" Disk usage : %s%%" % dk.percent)
# Get the total number of disks io Number , Read and write information

The first few lines are the disk information that the current system can access

Among them the first 1 That's ok mountpoint='/', Indicates the current local default disk

Among them the first 6 That's ok mountpoint='/Volumes/Extreme SSD', Indicates an external solid state mobile hard disk

Here is the local disk mountpoint='/' For example , Check disk usage ( Total capacity , Already used , Free capacity , Usage rate )

The meaning of each field in the last line is as follows :

read_count read IO Count
write_count Write IO Count
read_bytes read IO Number of bytes
write_bytes Write IO Number of bytes
read_time Disk read time
write_time Disk write time

Get the system network card information

#  Get total network IO Information 
# Send packet
print(" Send data bytes :", psutil.net_io_counters().bytes_sent,"bytes")
# Receive packets
print(" Receive data bytes :",psutil.net_io_counters().bytes_recv,"bytes")
# Output information of each network interface
net_counter = psutil.net_io_counters(pernic=True)
for i in net_counter:
print(" network card :"+i+" , Network card information :",net_counter[i])

You can get which network cards exist in the current machine , And how much traffic is sent and received

Check whether the local network card is consistent in the terminal

mac and linux System commands :ifconfig

window System commands :ipconfig

Some screenshots are as follows :

You can see that the network card data obtained by the program is consistent with that obtained by the local terminal

Get the current network speed

Obtain the current network speed by obtaining the traffic sent and received by the network card through the above program

s1 = psutil.net_io_counters(pernic=True)['en0']
s2 = psutil.net_io_counters(pernic=True)['en0']
result = s2.bytes_recv - s1.bytes_recv
print(str('%d' % (result / 1024)) + 'kb/s')

In code ['en0'] Said to get en0 Network card data , Because chenge's network card is en0

Finally, you can see the current network speed

Every 1 Seconds to execute the code can achieve real-time access to network speed

Other features

#  System Up Time 
# Convert to natural time format
print(datetime.datetime.fromtimestamp(psutil.boot_time ()).strftime("%Y-%m-%d %H: %M: %S"))
# Get the current system user login information
users = psutil.users()
for i in users:

You can get the startup time of this machine , And the current users

Today's article is here

If you have any questions, please leave a message below to discuss ~


1. This article introduces in detail python adopt psutil Get system information ( Memory , disk ,cpu etc. )

2. This article is only for readers to learn and use , Not for any other purpose !

Python Collect and monitor the system data ——psutil More articles about

  1. Python Data network collection 5-- Handle Javascript Redirection

    Python Data network collection 5-- Handle Javascript Redirection up to now , The only way we can communicate with the web server , Just send out HTTP Request to get the page . Some pages , We don't need to ask for it alone , You can interact with the web server ( Send and receive messages ...

  2. [Python monitor ]psutil Simple use of modules

    Easy to install pip install psutil The official website address is https://pythonhosted.org/psutil/ ( The document has detailed api) github The address is https://githu ...

  3. python Data analysis 4 Automatic data collection

    1 The importance of data collection Data collection is the basis of data mining , No data , There's no point in digging . A lot of times , How many data sources do we have , How much data , And the quality of the data , Will determine what results we will produce 2 Four types of acquisition methods 3 How to use open ...

  4. Why do you say Python It's a big data full stack development language

    Welcome to my personal website < Liu Jiang's blog and tutorial >:www.liujiangblog.com Mainly share Python And Django Tutorials and related blogs communication QQ Group :453131687 Link to the original text h ...

  5. python+Django Realization Nagios Add monitoring items automatically

    Recently, a number of machines have been installed in the machine room ( Yes 100 Around the table ), Need to use Nagios Monitor this batch of machines . The leader requires two days to complete the monitoring of all hosts . From the original experience , It can't be finished in two days . What to do with that ? As I thought before , It must be nag ...

  6. Big data learning —— Collect files to HDFS

    Collect requirements : For example, business system use log4j Generated logs , The content of the log keeps increasing , You need to collect the data added to the log file in real time hdfs According to the demand , First, define the following 3 The big thing l  Acquisition source , namely source—— Monitor file content updates :  ...

  7. python An instance method for obtaining system memory usage information

    psutil It's a cross platform library (http://code.google.com/p/psutil/), It is easy to get the system running process and system utilization ( Include CPU. Memory . disk . Network, etc ) Information . It is mainly used in system monitoring , ...

  8. C#+HtmlAgilityPack+XPath Take you to collect data ( Take collecting weather data as an example )

    First contact HtmlAgilityPack Is in 5 Years ago , Some accidents , Let me temporarily transfer from technical department to Sales Department , Responsible for setting up some processes and looking for potential customers , Finally, I found a lot of customer information in Alibaba , Very comprehensive , At first it was copied manually to Excel, ...

  9. Windows Next Python Read GRIB data

    I wrote an article before < be based on Python Of GRIB Data visualization > The article , Many bloggers asked me in the comments Windows How to read under the system GRIB data , Let me make a statement here . One . stay Windows Next Python Why can't ...

  10. Python Introduction to cloud system development —— frame foundation

    Django frame foundation This is what I learned from Songtian teacher of Beijing University of technology <Python Introduction to cloud system development > Course notes , Here I would like to thank the teacher for his wonderful explanation and guidance . 1.Django Introduction and installation Django It's a ...

Random recommendation

  1. Codeforces CF#628 Education 8 D. Magic Numbers

    D. Magic Numbers time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...

  2. Combox Control initialization techniques

    occasionally combox Drop down items are fixed , No need to do data binding , But if you use the string set editor directly ,SelectedValue It doesn't seem to work . So simply encapsulate /// <summary> ...

  3. C++ Read 、 Rotate and save bmp Image file programming

    I've met... Before bmp Reading and writing of documents . This blog is very good , Other content written is also worth learning . Reference resources :http://blog.csdn.net/xiajun07061225/article/details/6633938  learn ...

  4. public void Delete(List EntityList) where T : class, new() Type parameter constraint

    After searching, it is found that this is a type parameter constraint ,.NET There are five types of type parameter constraints supported : where T : struct | T It has to be a structure type where T : class T Must be a class (class) type whe ...

  5. HDU5029--Relief grain ( The tree chain splits + Line segment tree )

    The question :n A rootless tree of points ,m operations , For operation x y z, Express x To y On the way Each point Add one more z Numbers , Can be added repeatedly . Finally, output each point The number added the most times , If no output 0. Naked tree chain dissection ...

  6. The first 21 Yue di 6 God zhihu How to use 3 Month zero basic machine learning

    1. We should remember , The established fact must have its reason , If we can't understand it , I'm afraid we have to find the reason from ourselves . If you trade stocks , please remember , If the forecast doesn't match the market , It's the prediction that's wrong , Not the market https://www.cnblogs.co ...

  7. Forth Memory layout

    body, table{font-family: Microsoft YaHei } table{border-collapse: collapse; border: solid gray; border-width: 2p ...

  8. Nginx URL No slash after 301 Redirect

    There is a problem with development today , In fact, there was this problem before , But I never paid attention to , If you encounter problems in today's test, solve them . Problem situation : When I ask http://admindev.jingruiauto.com/store/views ...

  9. modify redis Persistent paths and logs route , modify kafka Log path

    redis Modify persistence path and log path vim redis.conf logfile /data/redis_cache/logs/redis.log # Log path dir /data/redis_cach ...

  10. use C Read system plaintext ( Source code attached )

    Get a good thing from a good friend System plaintext can be read Please use vc++ 6.0 compile #include <windows.h> #include <stdio.h> // // Vsbat[ ...