SoFunction
Updated on 2025-03-02

Advanced Python skills: Using psutil and subprocess to implement program monitoring and management

1. Introduction

In critical applications, it is very important to listen to the running status of the program because it can ensure smooth operation of the program. This article will introduce how to use Python to implement this function, mainly herepsutilandsubprocessModule. At the same time, a complete script case will be provided for reference, for monitoring and restarting the program when the target program is unexpectedly stopped.

Module introduction

subprocessModules are standard library modules in Python for creating and managing child processes. It allows youExecute system commandsorOther executable files, get their output, and interact with them. Here are somesubprocessBasic usage and examples of modules:

1. Run external commands

You can use()Functions to run external commands and wait for them to complete:

import subprocess

# Run a simple commandresult = (['ls', '-l'], capture_output=True, text=True)

# Print command outputprint()
  • ['ls', '-l']is a sample command that lists detailed file information for the current directory.
  • capture_output=TrueIndicates the standard output and standard error output of the capture command.
  • text=TrueIndicates that the output is returned as a text string, not bytes.

2. Execute commands in the background

If you want the command to be executed in the background without blocking the current process, you can usekind:

import subprocess

# Execute commands in the backgroundprocess = (['python', ''])

# Wait for the command to complete()

3. Get command output

If you need to get the output of the command, you can usesubprocess.check_output()Function:

import subprocess

# Get command outputoutput = subprocess.check_output(['echo', 'Hello, subprocess!'], text=True)

# Print Outprint(output)

4. Pass input to the command

Sometimes data needs to be passed to standard input of the command. Can be used()Method to implement:

import subprocess

# Start the command and pass the inputprocess = (['grep', 'Python'], stdin=, stdout=, text=True)

# Enter data into the commandoutput, _ = ('Python is awesome!')

# Print command outputprint(output)

5. Process the command to return the value

pass()or()The return value of the command can be obtained, usually the exit code of the command. This can help you determine whether the command is executed successfully.

Module introduction

psutilThe Python System and Process Utilities module is a cross-platform library that provides convenient interfaces to obtain system information and manage processes. It can be used to monitor the use of system resources, manage processes, and perform system management tasks. The following ispsutilSome main functions and usage examples of modules:

1. Installpsutil

First make sure you have installed itpsutilModule. If not installed, you can install it via pip:

pip install psutil

2. Obtain system information

usepsutilIt can easily obtain various information about the system, such asCPU usage, memory usage, disk partition informationwait.

import psutil

# Get the number of CPU logical corescpu_count = psutil.cpu_count(logical=True)
print(f"CPU Logical core number: {cpu_count}")

# Get memory usagememory = psutil.virtual_memory()
print(f"Total memory: { / 1024 / 1024} MB")
print(f"Memory used: { / 1024 / 1024} MB")

# Get disk partition informationdisk_partitions = psutil.disk_partitions()
for partition in disk_partitions:
    print(f"Partition equipment: {}, File system: {}")

3. Obtain process information

psutilIt can be used to obtain process information running in the system, including process list, CPU usage, memory usage, etc.

import psutil

# Get a list of all processesall_processes = list(psutil.process_iter())
for proc in all_processes[:5]:  # Print the first five processes    print(f"Process name: {()}, PID: {}")

# Get detailed information about the specified PID processpid = 1234  # Replace with the process you want to view PIDif psutil.pid_exists(pid):
    process = (pid)
    print(f"Process name称: {()}")
    print(f"Process Status: {()}")
    print(f"Process creation time: {process.create_time()}")
    print(f"process CPU Usage rate: {process.cpu_percent(interval=1)}%")
    print(f"process内存使用情况: {process.memory_info().rss / 1024 / 1024} MB")
else:
    print(f"PID {pid} 对应的process不存在。")

4. Process management operations

psutilIt also allows management operations on processes, such as terminating processes, sending signals, etc.

import psutil

# Terminate the process with the specified PIDpid_to_terminate = 5678  # Replace with the process you want to terminate PIDif psutil.pid_exists(pid_to_terminate):
    process = (pid_to_terminate)
    ()
    print(f"process {pid_to_terminate} Terminated。")
else:
    print(f"PID {pid_to_terminate} 对应的process不存在。")

5. Real-time monitoring of system resources

usepsutilIt can realize real-time monitoring of system resource usage, such as obtaining CPU usage in a loop:

import psutil

# Real-time monitoring of CPU usagewhile True:
    cpu_percent = psutil.cpu_percent(interval=1)
    print(f"current CPU Usage rate: {cpu_percent}%")

These examples showpsutilThe basic usage of modules in system information acquisition, process management and system resource monitoring. Depending on the specific needs, you can also use it in depth.psutilOther functions to implement more complex system management and monitoring tasks.

4. Practical application

Here is a usesubprocessA module to start and monitor a Python program sample code. Will use it later()to start the program and pass()to check if the process is still running. If the target program stops running, its return code will be obtained and the return code will be determined whether to restart the program.
The specific code is as follows:

import os
import subprocess
import sys
import time
import psutil  # Import the psutil module
def start_target_program(target_script):
    # Explicitly specify Python interpreter and environment variables    python_executable = 
    env = dict()
    env['PYTHONPATH'] = ":".join()  # Add the path of the current Python interpreter to the PYTHONPATH environment variable    # Start your Python program here    return ([python_executable, target_script], env=env)


def is_program_running(process):
    # Check if the program is running    return () is None

def bytes_to_readable(size_bytes):
    # Convert bytes to readable formats (KB, MB, GB)    for unit in ['', 'KB', 'MB', 'GB']:
        if size_bytes < 1024.0:
            return f"{size_bytes:.2f} {unit}"
        size_bytes /= 1024.0

def monitor_process(target_script):
    # Start the monitored program    target_program = start_target_program(target_script)
    while True:
        # Check and print CPU utilization        cpu_percent = psutil.cpu_percent(interval=1)
        print(f"current CPU Utilization rate:{cpu_percent}%")

        # Get and print memory information        memory_info = psutil.virtual_memory()
        total_memory = bytes_to_readable(memory_info.total)
        available_memory = bytes_to_readable(memory_info.available)
        print(f"Total memory: {total_memory}")
        print(f"Available memory: {available_memory}")

        # Get and print disk partition information        disk_partitions = psutil.disk_partitions()
        print("Disk Partition Information:")
        for partition in disk_partitions:
            print(f"    Partition:{} Mounting point:{}")

        # Check if the program is running        if not is_program_running(target_program):
            # Check the program end status (whether it ends normally)            if target_program.returncode == 0:
                print("The monitored program has been closed normally.")
                break
            else:
                print(f"The monitored program has been closed,Return to the code:{target_program.returncode}")
                print("Restarting...")
                target_program = start_target_program(target_script)
        else:
            print("The monitored program runs normally...")

        # Listen every 10 minutes        (600)

if __name__ == '__main__':
    # It is necessary to note that the path of the monitored script and the monitoring program are kept in the same directory.    target_script = input("Please enter the script name () you need to monitor:")
    monitor_process(target_script)

By combining the subprocess and psutil modules, monitoring and management of target programs can be easily achieved.

This article provides a simple example code showing howStart, monitor and restartA program. Hope this helps you better understand and use Python for system and process management.

Summarize

This is the article about advanced Python skills that use psutil and subprocess to implement program monitoring and management. For more related contents of psutil and subprocess program monitoring and management, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!