The benefits of using this library include
- Because psutil API resembles UNIX process management command line utilities the developers find themselves home
- Pythonic, easy to use, API
- Good documentation
psutil is maintained by Giampaolo Rodola and Jay Loden.
Below is a short example what you can do with psutil. It checks if the current operating system is running Apache (web server) process and this process is listening to particular TCP/IP ports. The use case could be e.g. per-requirements check that the software can be deployed against a particular system.
import psutil def is_apache_running_in_ports(process_name="apache", ports=(80, 443)): """ Check if a local Apache instance is running and listening to certain ports. :param ports: List of ports Apache should be listening to (all ports must be included) """ ports_to_go = list(ports) # Iterate over all system processes (ps) for proc in psutil.process_iter(): if proc.name != process_name: # Not target process continue # Iterate over all ports this process is listening to for con in proc.get_connections(): # Tuple ip, port port = con.local_address if port in ports_to_go: ports_to_go.remove(port) # Did we find all ports we wanted to return len(ports_to_go) == 0Note: When installing psutil be sure that you follow the Python best practices: sudo-free virtualenv installation.