【问题标题】:How to get the pid of process using python如何使用python获取进程的pid
【发布时间】:2019-08-14 12:21:24
【问题描述】:

我有一个包含firefox , atom , gnome-shell的任务列表文件

我的代码

import psutil
with open('tasklist', 'r') as task:
    x = task.read()
    print (x)

print ([p.info for p in psutil.process_iter(attrs=['pid', 'name']) if x in p.info['name']])

想要的

[{'pid': 413, 'name': 'firefox'}]
[{'pid': 8416, 'name': 'atom'}]
[{'pid': 2322, 'name': 'gnome-shell'}]

【问题讨论】:

  • 实际的输出是?

标签: python process pid psutil


【解决方案1】:

类似于上面的答案,但从问题来看,您似乎只对所有正在运行的任务的子集感兴趣(例如 firefox、atom 和 gnome-shell)

您可以将您感兴趣的任务放入一个列表中。然后循环遍历所有流程,仅将与您的列表匹配的那些附加到最终输出中,如下所示:

import psutil

tasklist=['firefox','atom','gnome-shell']
out=[]

for proc in psutil.process_iter():
    if any(task in proc.name() for task in tasklist):
        out.append([{'pid' : proc.pid, 'name' : proc.name()}])

这将为您提供所需的列表列表输出,其中每个列表都有一个带有 pid 和 name 键的字典...您可以将输出调整为您喜欢的任何格式

您要求的确切输出可以通过以下方式获得:

for o in out[:]:
    print(o)

【讨论】:

    【解决方案2】:
    import wmi  # pip install wmi
    
    c = wmi.WMI()
    tasklist = []
    
    for process in c.Win32_Process():
        tasklist.append({'pid': process.ProcessId, 'name': process.Name})
    print(tasklist)
    

    对于 Unix:

    import psutil
    
    tasklist = []
    
    for proc in psutil.process_iter():
        try:
            tasklist.append({'pid': proc.name(), 'name': proc.pid})
        except:
            pass
    print(tasklist)
    

    【讨论】:

    • gnome-shell 进程的存在来看,看起来 OP 正在使用 Linux。
    • @crayxt 认为你是对的。更新了两种情况的答案! :)
    猜你喜欢
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2021-08-08
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多