This article describes the use of psutil in Python to obtain process information about the system.
1 Overview
psutil is a process and system toolset module for Python. Using psutil, you can get information about processes in the operating system from within Python.
The rpm package used in this article is: python2-psutil.x86_64, which is defined as follows:
python2-psutil.x86_64 : A process and system utilities module for Python
2 Code Example
A sample program is given below, which has two functions: to get information about all processes in the OS and print it out; and to kill the specified process. The code (process_oper_test1.py) is as follows:
#!/usr/bin/python # File name: process_oper_test1.py # Description: some process operations # Created on: 2018-07-19 # Author: liitdar import psutil import os import signal print("----------------------------- show all processes info --------------------------------") # show processes info pids = () for pid in pids: p = (pid) # get process name according to pid process_name = () print("Process name is: %s, pid is: %s" %(process_name, pid)) print("----------------------------- kill specific process --------------------------------") pids = () for pid in pids: p = (pid) # get process name according to pid process_name = () # kill process "sleep_test1" if 'sleep_test1' == process_name: print("kill specific process: name(%s)-pid(%s)" %(process_name, pid)) (pid, ) exit(0)
Test the above code below.
We have a process named "sleep_test1" running on our system as follows:
Then we run the Python sample program using the following command:
[root@node1 /opt/liitdar/mydemos/simples]# python process_oper_test1.py
(The results of the (partial) run are as follows:
At this point, we query the "sleep_test1" process, and find that the process no longer exists, which means that the Python sample program functions normally. This means that the Python example program is functioning correctly:
The above article in Python to get the process information of the operating system is all that I have shared with you, I hope to give you a reference, and I hope you will support me more.