python实时监控系统进程
时间: 2024-06-16 16:02:28 浏览: 15
在Python中,实时监控系统进程通常可以通过使用一些第三方库如psutil、multiprocessing等来实现。以下是一个简单的概述:
1. psutil库:这是最常用的库之一,用于获取系统和进程信息。你可以用它来检测运行中的进程,获取它们的CPU、内存、磁盘使用情况等。例如:
```python
import psutil
def monitor_process(pid):
process = psutil.Process(pid)
while True:
print(f"Process {pid} CPU usage: {process.cpu_percent()}%")
print(f"Memory usage: {process.memory_info().rss / 1024 ** 2} MB")
time.sleep(1) # 每秒更新一次
# 要监控的进程ID
pid_to_monitor = 1234
monitor_process(pid_to_monitor)
```
2. `multiprocessing`模块:如果你想要在子进程中监控其他进程,可以使用`Pool`或`Process`对象。这允许你启动一个新进程并监视其状态。
```python
from multiprocessing import Process, freeze_support
def worker(pid):
# 进行一些操作,同时返回PID供主进程监控
return pid
def monitor(worker_func, target_pid):
child = Process(target=worker_func)
child.start()
child.join() # 等待子进程结束
print(f"Process {target_pid} completed")
freeze_support() # 必要的,仅限于Windows平台
target_pid = 5678
monitor(worker, target_pid)
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)