【问题标题】:Search for particular data stored in variable搜索存储在变量中的特定数据
【发布时间】:2022-11-14 14:37:57
【问题描述】:

我试图找到在我的系统上运行的特殊进程。为此,拉出目前在我的系统上运行的所有进程并将其存储在一个名为“名称”的变量中。现在我想解析存储在这个“名称”变量中的数据,并找到我需要的特定过程。

import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
# get rid of extra " and split into lines
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
# make dict with proc names as keys and dicts with the extra nfo as values
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
    print(name)

这是我的代码。

【问题讨论】:

    标签: python parsing


    【解决方案1】:

    我想我还没有得到你的问题。如果您遍历所有进程,则可以通过当前进程的名称与您正在查找的进程签入每个循环。也许不仅仅是一个简单的比较,而是使用正则表达式。

    例如进程 WhatsApp.exe:

    import subprocess
    import re
    
    output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
    
    # get rid of extra " and split into lines
    output = output.replace('"', '').split('
    ')
    keys = output[0].split(',')
    proc_list = [i.split(',') for i in output[1:] if i]
    
    # make dict with proc names as keys and dicts with the extra nfo as values
    proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
    
    for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
        proc = re.search("[wW]hats[Aa]pp", name) 
    
        if proc is not None:
            print(name)
    

    另一种方法是没有“.exe”和小写进程的比较。 对于名称,排序后的值(proc_dict.items(), key=lambda x: x[0].lower()):

        if name[:-4].lower() == "whatsapp":
            print(name)
    

    第二种方法可能很危险,如果你正在寻找一个不是 .exe 的进程(如果 Windows 中有类似的东西)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 2012-08-27
      • 1970-01-01
      • 2012-04-13
      相关资源
      最近更新 更多