在Python中,可以使用psutil
庫來管理系統(tǒng)進程。psutil
是一個跨平臺的庫,可以方便地獲取系統(tǒng)進程信息、CPU和內(nèi)存使用情況等。首先,確保已經(jīng)安裝了psutil
庫,如果沒有安裝,可以使用以下命令安裝:
pip install psutil
接下來,我將向您展示如何使用psutil
庫來管理系統(tǒng)進程。
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())
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中管理系統(tǒng)進程。您可以根據(jù)需要修改這些示例以滿足您的需求。