|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +""" |
| 4 | +Process Monitor Script |
| 5 | +
|
| 6 | +This script monitors CPU and RAM usage of a specified process using its PID. |
| 7 | +Metrics are recorded to a CSV file until the process terminates. |
| 8 | +""" |
| 9 | + |
| 10 | +import argparse |
| 11 | +import csv |
| 12 | +import os |
| 13 | +import sys |
| 14 | +import time |
| 15 | + |
| 16 | +from datetime import datetime |
| 17 | +from psutil import Process, NoSuchProcess, pid_exists |
| 18 | + |
| 19 | + |
| 20 | +class ProcessMonitor: |
| 21 | + """Class to monitor process metrics including CPU and RAM usage.""" |
| 22 | + |
| 23 | + def __init__(self, pid: int, interval: float = 0.1): |
| 24 | + """ |
| 25 | + Initialize the ProcessMonitor. |
| 26 | +
|
| 27 | + Args: |
| 28 | + pid (int): Process ID to monitor |
| 29 | + interval (float): Sampling interval in seconds |
| 30 | + """ |
| 31 | + self.pid = pid |
| 32 | + self.interval = interval |
| 33 | + self.output_file = f'process_{pid}_metrics.txt' |
| 34 | + |
| 35 | + def get_process_metrics(self) -> tuple[str, float, float] | None: |
| 36 | + """ |
| 37 | + Collect current process metrics. |
| 38 | +
|
| 39 | + Returns: |
| 40 | + tuple: (timestamp, memory_mb, cpu_percent) or None if process not found |
| 41 | + """ |
| 42 | + try: |
| 43 | + process = Process(self.pid) |
| 44 | + cpu_percent = process.cpu_percent(interval=0.1) |
| 45 | + memory_kb = process.memory_info().rss / 1024 |
| 46 | + timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] |
| 47 | + |
| 48 | + return timestamp, memory_kb, cpu_percent |
| 49 | + |
| 50 | + except NoSuchProcess: |
| 51 | + print(f"Process with PID {self.pid} no longer exists") |
| 52 | + return None |
| 53 | + except Exception as e: |
| 54 | + print(f"Error: {e}") |
| 55 | + return None |
| 56 | + |
| 57 | + def write_to_csv(self, data: tuple[str, float, float]) -> None: |
| 58 | + """ |
| 59 | + Write metrics to CSV file. |
| 60 | +
|
| 61 | + Args: |
| 62 | + data (tuple): (timestamp, memory_kb, cpu_percent) |
| 63 | + """ |
| 64 | + file_exists = os.path.isfile(self.output_file) |
| 65 | + |
| 66 | + with open(self.output_file, 'a', newline='', encoding='utf-8') as csvfile: |
| 67 | + writer = csv.writer(csvfile) |
| 68 | + |
| 69 | + if not file_exists: |
| 70 | + writer.writerow(['Timestamp', 'RAM (KB)', 'CPU (%)']) |
| 71 | + |
| 72 | + writer.writerow(data) |
| 73 | + |
| 74 | + def record_metrics_until_process_ends(self) -> None: |
| 75 | + """Start monitoring the process and recording metrics.""" |
| 76 | + print(f"Starting monitoring of PID {self.pid}") |
| 77 | + print(f"Writing data to {self.output_file}") |
| 78 | + |
| 79 | + try: |
| 80 | + while True: |
| 81 | + metrics = self.get_process_metrics() |
| 82 | + |
| 83 | + if metrics is None: |
| 84 | + print("Process monitoring ended") |
| 85 | + break |
| 86 | + |
| 87 | + self.write_to_csv(metrics) |
| 88 | + |
| 89 | + time.sleep(self.interval) |
| 90 | + |
| 91 | + except KeyboardInterrupt: |
| 92 | + print("\nInterrupted by user") |
| 93 | + except Exception as e: |
| 94 | + print(f"Error: {e}") |
| 95 | + |
| 96 | + |
| 97 | +def parse_arguments() -> argparse.Namespace: |
| 98 | + """ |
| 99 | + Parse command line arguments. |
| 100 | +
|
| 101 | + Returns: |
| 102 | + argparse.Namespace: Parsed command line arguments |
| 103 | + """ |
| 104 | + parser = argparse.ArgumentParser( |
| 105 | + description='Monitor CPU and RAM usage of a process.', |
| 106 | + formatter_class=argparse.ArgumentDefaultsHelpFormatter |
| 107 | + ) |
| 108 | + |
| 109 | + parser.add_argument( |
| 110 | + 'pid', |
| 111 | + type=int, |
| 112 | + help='Process ID to monitor' |
| 113 | + ) |
| 114 | + |
| 115 | + parser.add_argument( |
| 116 | + '-i', '--interval', |
| 117 | + type=float, |
| 118 | + default=0.1, |
| 119 | + help='Sampling interval in seconds' |
| 120 | + ) |
| 121 | + |
| 122 | + return parser.parse_args() |
| 123 | + |
| 124 | + |
| 125 | +def validate_args(args: argparse.Namespace) -> None: |
| 126 | + """ |
| 127 | + Checks the validity of arguments. |
| 128 | +
|
| 129 | + Raises an error if any of the args are invalid. |
| 130 | + """ |
| 131 | + # Validate PID |
| 132 | + if not pid_exists(args.pid): |
| 133 | + raise ValueError(f"Error: Process with PID {args.pid} does not exist") |
| 134 | + |
| 135 | + # Validate interval |
| 136 | + if args.interval <= 0: |
| 137 | + raise ValueError("Error: Interval must be greater than 0") |
| 138 | + |
| 139 | + |
| 140 | +def main() -> int: |
| 141 | + """ |
| 142 | + Main function to run the process monitor. |
| 143 | +
|
| 144 | + Returns: |
| 145 | + int: Exit code (0 for success, 1 for error) |
| 146 | + """ |
| 147 | + try: |
| 148 | + args = parse_arguments() |
| 149 | + |
| 150 | + validate_args(args) |
| 151 | + |
| 152 | + monitor = ProcessMonitor(args.pid, args.interval) |
| 153 | + monitor.record_metrics_until_process_ends() |
| 154 | + return 0 |
| 155 | + |
| 156 | + except Exception as e: |
| 157 | + print(f"Error: {e}") |
| 158 | + return 1 |
| 159 | + |
| 160 | + |
| 161 | +if __name__ == "__main__": |
| 162 | + sys.exit(main()) |
0 commit comments