search
HomeBackend DevelopmentPython TutorialHow to use psutil to obtain system information in Python

3. psutil

Using Python to write scripts to simplify daily operation and maintenance work is an important use of Python. Under Linux, there are many system commands that allow us to monitor the running status of the system at all times, such as ps, top, free, etc. To obtain these system information, Python can call and obtain the results through the subprocess module. But it seems very troublesome to do so, especially if you have to write a lot of parsing code.

Another good way to get system information in Python is to use the psutil third-party module. As the name suggests, psutil = process and system utilities. It can not only realize system monitoring through one or two lines of code, but also can be used across platforms. It supports Linux/UNIX/OSX/Windows, etc., and is indispensable for system administrators and operation and maintenance partners. Required module.

1. Install psutil

If Anaconda is installed, psutil is already available. Otherwise, you need to install it through pip on the command line:

$ pip install psutil

If you encounter a Permission denied installation failure, please add sudo and try again.

2. Obtain CPU information

Let’s first obtain CPU information:

>>> import psutil
>>> psutil.cpu_count() # CPU逻辑数量
4
>>> psutil.cpu_count(logical=False) # CPU物理核心
2
# 2说明是双核超线程, 4则是4核非超线程

How to use psutil to obtain system information in Python

Statistics on CPU user/system/idle time :

>>> psutil.cpu_times()
scputimes(user=10963.31, nice=0.0, system=5138.67, idle=356102.45)

Then implement the CPU usage similar to the top command, refresh once per second, 10 times in total:

>>> for x in range(10):
...     print(psutil.cpu_percent(interval=1, percpu=True))
... 
[14.0, 4.0, 4.0, 4.0]
[12.0, 3.0, 4.0, 3.0]
[8.0, 4.0, 3.0, 4.0]
[12.0, 3.0, 3.0, 3.0]
[18.8, 5.1, 5.9, 5.0]
[10.9, 5.0, 4.0, 3.0]
[12.0, 5.0, 4.0, 5.0]
[15.0, 5.0, 4.0, 4.0]
[19.0, 5.0, 5.0, 4.0]
[9.0, 3.0, 2.0, 3.0]

3. Obtain memory information

Use psutil to obtain physical memory and swap memory information, respectively:

>>> psutil.virtual_memory()
svmem(total=8589934592, available=2866520064, percent=66.6, used=7201386496, free=216178688, active=3342192640, inactive=2650341376, wired=1208852480)
>>> psutil.swap_memory()
sswap(total=1073741824, used=150732800, free=923009024, percent=14.0, sin=10705981440, sout=40353792)

returns an integer in bytes. You can see that the total memory size is 8589934592 = 8 GB, and 7201386496 = 6.7 GB has been used. , 66.6% is used.

The swap area size is 1073741824 = 1 GB.

Get disk information

You can get disk partition, disk usage and disk IO information through psutil:

>>> psutil.disk_partitions() # 磁盘分区信息
[sdiskpart(device='/dev/disk1', mountpoint='/', fstype='hfs', opts='rw,local,rootfs,dovolfs,journaled,multilabel')]
>>> psutil.disk_usage('/') # 磁盘使用情况
sdiskusage(total=998982549504, used=390880133120, free=607840272384, percent=39.1)
>>> psutil.disk_io_counters() # 磁盘IO
sdiskio(read_count=988513, write_count=274457, read_bytes=14856830464, write_bytes=17509420032, read_time=2228966, write_time=1618405)

You can see that the disk '/'## The total capacity of # is 998982549504 = 930 GB, 39.1% used. The file format is HFS, opts contains rw to indicate readability and writability, and journaled indicates support for journaling.

4. Obtain network information

psutil can obtain the network interface and network connection information:

>>> psutil.net_io_counters() # 获取网络读写字节/包的个数
snetio(bytes_sent=3885744870, bytes_recv=10357676702, packets_sent=10613069, packets_recv=10423357, errin=0, errout=0, dropin=0, dropout=0)
>>> psutil.net_if_addrs() # 获取网络接口信息
{
  &#39;lo0&#39;: [snic(family=<AddressFamily.AF_INET: 2>, address=&#39;127.0.0.1&#39;, netmask=&#39;255.0.0.0&#39;), ...],
  &#39;en1&#39;: [snic(family=<AddressFamily.AF_INET: 2>, address=&#39;10.0.1.80&#39;, netmask=&#39;255.255.255.0&#39;), ...],
  &#39;en0&#39;: [...],
  &#39;en2&#39;: [...],
  &#39;bridge0&#39;: [...]
}
>>> psutil.net_if_stats() # 获取网络接口状态
{
  &#39;lo0&#39;: snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=16384),
  &#39;en0&#39;: snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=1500),
  &#39;en1&#39;: snicstats(...),
  &#39;en2&#39;: snicstats(...),
  &#39;bridge0&#39;: snicstats(...)
}

To obtain the current network connection information, use

net_connections():

>>> psutil.net_connections()
Traceback (most recent call last):
  ...
PermissionError: [Errno 1] Operation not permitted

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  ...
psutil.AccessDenied: psutil.AccessDenied (pid=3847)

You may get an

AccessDenied error. The reason is that psutil also needs to use the system interface to obtain information, and obtaining network connection information requires root privileges. In this case, you can exit Python interactive environment, use sudo to restart:

$ sudo python3
Password: ******
Python 3.8 ... on darwin
Type "help", ... for more information.
>>> import psutil
>>> psutil.net_connections()
[
    sconn(fd=83, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip=&#39;::127.0.0.1&#39;, port=62911), raddr=addr(ip=&#39;::127.0.0.1&#39;, port=3306), status=&#39;ESTABLISHED&#39;, pid=3725),
    sconn(fd=84, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip=&#39;::127.0.0.1&#39;, port=62905), raddr=addr(ip=&#39;::127.0.0.1&#39;, port=3306), status=&#39;ESTABLISHED&#39;, pid=3725),
    sconn(fd=93, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip=&#39;::&#39;, port=8080), raddr=(), status=&#39;LISTEN&#39;, pid=3725),
    sconn(fd=103, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip=&#39;::127.0.0.1&#39;, port=62918), raddr=addr(ip=&#39;::127.0.0.1&#39;, port=3306), status=&#39;ESTABLISHED&#39;, pid=3725),
    sconn(fd=105, family=<AddressFamily.AF_INET6: 30>, type=1, ..., pid=3725),
    sconn(fd=106, family=<AddressFamily.AF_INET6: 30>, type=1, ..., pid=3725),
    sconn(fd=107, family=<AddressFamily.AF_INET6: 30>, type=1, ..., pid=3725),
    ...
    sconn(fd=27, family=<AddressFamily.AF_INET: 2>, type=2, ..., pid=1)
]

5. Obtain process information

You can obtain detailed information of all processes through psutil:

>>> psutil.pids() # 所有进程ID
[3865, 3864, 3863, 3856, 3855, 3853, 3776, ..., 45, 44, 1, 0]
>>> p = psutil.Process(3776) # 获取指定进程ID=3776,其实就是当前Python交互环境
>>> p.name() # 进程名称
&#39;python3.6&#39;
>>> p.exe() # 进程exe路径
&#39;/Users/michael/anaconda3/bin/python3.6&#39;
>>> p.cwd() # 进程工作目录
&#39;/Users/michael&#39;
>>> p.cmdline() # 进程启动的命令行
[&#39;python3&#39;]
>>> p.ppid() # 父进程ID
3765
>>> p.parent() # 父进程
<psutil.Process(pid=3765, name=&#39;bash&#39;) at 4503144040>
>>> p.children() # 子进程列表
[]
>>> p.status() # 进程状态
&#39;running&#39;
>>> p.username() # 进程用户名
&#39;michael&#39;
>>> p.create_time() # 进程创建时间
1511052731.120333
>>> p.terminal() # 进程终端
&#39;/dev/ttys002&#39;
>>> p.cpu_times() # 进程使用的CPU时间
pcputimes(user=0.081150144, system=0.053269812, children_user=0.0, children_system=0.0)
>>> p.memory_info() # 进程使用的内存
pmem(rss=8310784, vms=2481725440, pfaults=3207, pageins=18)
>>> p.open_files() # 进程打开的文件
[]
>>> p.connections() # 进程相关网络连接
[]
>>> p.num_threads() # 进程的线程数量
1
>>> p.threads() # 所有线程信息
[pthread(id=1, user_time=0.090318, system_time=0.062736)]
>>> p.environ() # 进程环境变量
{&#39;SHELL&#39;: &#39;/bin/bash&#39;, &#39;PATH&#39;: &#39;/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:...&#39;, &#39;PWD&#39;: &#39;/Users/michael&#39;, &#39;LANG&#39;: &#39;zh_CN.UTF-8&#39;, ...}
>>> p.terminate() # 结束进程
Terminated: 15 <-- 自己把自己结束了

Similar to obtaining a network connection, obtaining a root user's process requires root permissions. When starting the Python interactive environment or the

.py file, sudo permissions are required.

psutil also provides a

test() function, which can simulate the effect of the ps command:

$ sudo python3
Password: ******
Python 3.6.3 ... on darwin
Type "help", ... for more information.
>>> import psutil
>>> psutil.test()
USER         PID %MEM     VSZ     RSS TTY           START    TIME  COMMAND
root           0 24.0 74270628 2016380 ?             Nov18   40:51  kernel_task
root           1  0.1 2494140    9484 ?             Nov18   01:39  launchd
root          44  0.4 2519872   36404 ?             Nov18   02:02  UserEventAgent
root          45    ? 2474032    1516 ?             Nov18   00:14  syslogd
root          47  0.1 2504768    8912 ?             Nov18   00:03  kextd
root          48  0.1 2505544    4720 ?             Nov18   00:19  fseventsd
_appleeven    52  0.1 2499748    5024 ?             Nov18   00:00  appleeventsd
root          53  0.1 2500592    6132 ?             Nov18   00:02  configd
...

The above is the detailed content of How to use psutil to obtain system information in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.