【问题标题】:Get list of running windows applications using python使用python获取正在运行的windows应用程序列表
【发布时间】:2019-07-16 14:19:50
【问题描述】:

我只想返回那些在 Windows 任务管理器的“应用程序”类别下列出的应用程序,而不是所有正在运行的进程。下面的脚本返回我不想要的所有进程。如何根据我的要求修改此代码?

import subprocess
cmd = 'WMIC PROCESS get Caption,Commandline,Processid'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
    print(line)

【问题讨论】:

    标签: python windows subprocess


    【解决方案1】:

    您可以使用 powershell 而不是 WMIC 来获取所需的应用程序列表:

    import subprocess
    cmd = 'powershell "gps | where {$_.MainWindowTitle } | select Description'
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    for line in proc.stdout:
        if line.rstrip():
            # only print lines that are not empty
            # decode() is necessary to get rid of the binary string (b')
            # rstrip() to remove `\r\n`
            print(line.decode().rstrip())
    

    得到一个空表?

    请注意,在某些系统上,这会导致一个空表,因为描述似乎是空的。在这种情况下,您可能想尝试不同的列,例如 ProcessName,从而得到以下命令:

    cmd = 'powershell "gps | where {$_.MainWindowTitle } | select ProcessName'
    

    需要输出中的更多列/信息?

    如果您想要更多信息,例如process idpath,整理输出需要更多的努力。

    import subprocess
    cmd = 'powershell "gps | where {$_.MainWindowTitle } | select Description,Id,Path'
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    for line in proc.stdout:
        if not line.decode()[0].isspace():
            print(line.decode().rstrip())
    

    cmd 的输出是格式化为表格的文本。不幸的是,它返回的不仅仅是我们需要的应用程序,所以我们需要整理一下。所有需要的应用程序在 Description 列中都有一个条目,因此我们只需检查第一个字符是否为空格。

    这就是原始表的样子(isspace() if 子句之前):

    Description                                    Id Path
    -----------                                    -- ----
                                                  912
                                                 9124
                                                11084
    Microsoft Office Excel                       1944 C:\Program Files (x86)\Microsoft Office\Office12\EXCEL.EXE
    

    【讨论】:

    • 如果我想使用 python 关闭其中一个程序,我该怎么做?
    猜你喜欢
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 2019-03-25
    • 1970-01-01
    相关资源
    最近更新 更多