Python psutil example

Carlos 18 Published: 11/19/2024

Python psutil example

Here is an example of using the psutil library in Python to interact with processes:

Firstly, you need to install the psutil library if you haven't done so already. You can do this by running the following command in your terminal:

pip install psutil

Once installed, you can use the following code as a starting point for interacting with processes using psutil.

Here is an example of how to list all the currently running processes:

import psutil
Get a list of all running processes

for proc in psutil.process_iter():

try:

pinfo = proc.as_dict()

print("Process Name: ", pinfo['name'])

print("Process ID: ", pinfo['pid'])

except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):

pass

In this example, we use a loop to iterate through all the running processes and get their name and process id. The as_dict() method returns a dictionary containing information about the process.

You can also use psutil to interact with specific processes:

# Get the process object

p = psutil.Process(1234) # Replace with your desired process ID

Check if the process is running

print("Is the process running? ", p.is_running())

Terminate the process (if possible)

try:

p.terminate()

except PermissionError:

print("Permission denied to terminate the process. ")

Get a list of all threads in this process

for tid, thrd_info in enumerate(p.threads()):

print(f"Thread ID {tid}: {thrd_info.pid}")

Get a list of all connections in this process

for conn in p.connections():

print(f"Connection: {conn.status} - {conn.laddr}:{conn.raddr}")

In this example, we use the Process object to interact with a specific process by its process id. We can check if the process is running, terminate it (if possible), get a list of all threads in this process, and get a list of all connections in this process.

These are just a few examples of what you can do with psutil. It has many more features that allow for detailed information about processes, threads, users, etc., making it useful for monitoring system resources and debugging issues.

I hope this helps!

Python psutil memory usage

Here's an explanation of how to use the Python library psutil to get memory usage information:

What is psutil?

psutil (process and system utilities) is a cross-platform library for retrieving information about running processes and system utilization in Python. It provides an easy-to-use interface for accessing various aspects of system performance, including CPU, memory, network, and disk statistics.

Getting Memory Usage with psutil

To get the current memory usage using psutil, you can use the following code:

import psutil
Get the current process

process = psutil.Process()

Get the memory information (in bytes)

memory_info = process.memory_info()

print("Memory Information:")

print(f"RSS: {memory_info.rss / 1024 **3} GB") # Resident Set Size (RSS) in GB

print(f"VMS: {memory_info.vms / 1024 **3} GB") # Virtual Memory Size (VMS) in GB

This code will print the RSS (Resident Set Size, i.e., the amount of physical memory used by the process) and VMS (Virtual Memory Size, i.e., the total memory usage, including both resident and swapped out pages).

Breaking Down the Memory Usage

The memory_info() function returns a svmem object that contains information about the process's memory usage. Here are some key fields:

rss: The Resident Set Size (RSS) in bytes. This is the amount of physical memory used by the process. vms: The Virtual Memory Size (VMS) in bytes. This is the total memory usage, including both resident and swapped out pages. shared: The shared memory size in bytes. This represents the amount of memory that is shared with other processes. text: The text segment size in bytes. This represents the amount of memory used by the process's code (e.g., the executable). lib: The library segment size in bytes. This represents the amount of memory used by the process's libraries. data: The data segment size in bytes. This represents the amount of memory used by the process's initialized data.

By analyzing these fields, you can gain insights into how your Python script is using system resources and potentially identify performance bottlenecks or areas for optimization.

Additional Tips

To get a more comprehensive understanding of memory usage, consider running your Python script multiple times and observing the memory usage patterns. You may also want to use psutil in conjunction with other tools, such as htop or glances, to visualize system resource utilization.

Remember that psutil provides many more features beyond just memory usage, so feel free to explore its documentation and discover how you can leverage this powerful library for your own projects!