温馨提示×

python linux进程管理怎样做

小樊
81
2024-11-15 14:41:00
栏目: 编程语言

在Python中,可以使用psutil库来管理系统进程。psutil是一个跨平台的库,可以方便地获取系统进程信息、CPU和内存使用情况等。首先,确保已经安装了psutil库,如果没有安装,可以使用以下命令安装:

pip install psutil

接下来,我将向您展示如何使用psutil库来管理系统进程。

  1. 获取所有进程列表:
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())
  1. 根据进程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)
  1. 查找特定名称的进程:
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")
  1. 杀死特定进程:
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中管理系统进程。您可以根据需要修改这些示例以满足您的需求。

0