在Python中,可以使用psutil
库来管理系统进程。psutil
是一个跨平台的库,可以方便地获取系统进程信息、CPU和内存使用情况等。首先,确保已经安装了psutil
库,如果没有安装,可以使用以下命令安装:
pip install psutil
接下来,我将向您展示如何使用psutil
库来管理系统进程。
- 获取所有进程列表:
import psutil def get_all_processes(): processes = [] for process in psutil.process_iter(): processes.append(process) return processes all_processes = get_all_processes() for process in all_processes: print(process.pid, process.name())
- 根据进程ID(PID)获取进程信息:
import psutil def get_process_info(pid): process = psutil.Process(pid) return process.as_dict(attrs=['pid', 'name', 'username', 'cpu_times', 'memory_info']) pid = 12345 process_info = get_process_info(pid) print(process_info)
- 查找特定名称的进程:
import psutil def find_process_by_name(name): for process in psutil.process_iter(): if process.name() == name: return process return None process_name = "python" process = find_process_by_name(process_name) if process: print(f"Found process with PID {process.pid} and name {process.name()}") else: print(f"Process with name {process_name} not found")
- 杀死特定进程:
import psutil def kill_process_by_pid(pid): process = psutil.Process(pid) if process.is_running(): process.terminate() print(f"Process with PID {pid} terminated") else: print(f"Process with PID {pid} is not running") pid = 12345 kill_process_by_pid(pid)
这些示例展示了如何使用psutil
库在Python中管理系统进程。您可以根据需要修改这些示例以满足您的需求。