溫馨提示×

python linux進程管理怎樣做

小樊
81
2024-11-15 14:41:00
欄目: 編程語言

在Python中,可以使用psutil庫來管理系統(tǒng)進程。psutil是一個跨平臺的庫,可以方便地獲取系統(tǒng)進程信息、CPU和內(nèi)存使用情況等。首先,確保已經(jīng)安裝了psutil庫,如果沒有安裝,可以使用以下命令安裝:

pip install psutil

接下來,我將向您展示如何使用psutil庫來管理系統(tǒng)進程。

  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. 根據(jù)進程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中管理系統(tǒng)進程。您可以根據(jù)需要修改這些示例以滿足您的需求。

0