Skip to main content
 首页 » 编程设计

python之在 Python 中查看所有系统进程

2024年11月01日9rubylouvre

我正在尝试使用 Python 收集有关我的操作系统 (Ubuntu) 中进程的一些统计信息(生命周期、开始时间/结束时间等),

任务之一:我写了一个函数,它获取系统中进程的名称和 ID,但它很丑。

def get_processes(): 
    p = subprocess.Popen(['ps', '-e'], stdout=subprocess.PIPE) 
    raw_string, e = p.communicate() 
    strings_arr = raw_string.split('\n') 
    strings_arr = strings_arr[1:] 
    processes_dict = {} 
    # Example of ps -e ansewer:  7 ?        00:00:00 watchdog/0 
    for string in strings_arr: 
        splted = string.split() 
        key, value = None, None 
        if len(splted) == 0: continue 
        for item in splted:#looking for process id 
            if item.isdigit(): 
                key = int(item) 
                break 
        value = splted[-1] # looking for process name 
        processes_dict[key] = value 
    return processes_dict 

谁能把它做得漂亮或者提出更好的解决方案? PS对不起我的写作错误。英语不是我的母语。

请您参考如下方法:

获取psutil .这样的事情会给你类似的结果,

{process.pid: process.exe for process in psutil.process_iter() if process.pid}