psutil is a Python library and API for UNIX system administration utilities. It provides Pythonic API e.g. for top, lsof, netstat and kill like tasks.
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
- Cross-platform
- 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[1] 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.
More examples at psutil homepage.
Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+