gpt4 book ai didi

python - 使用 python 获取正在运行的 Windows 应用程序列表

转载 作者:可可西里 更新时间:2023-11-01 09:32:10 27 4
gpt4 key购买 nike

我只想返回那些在 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)

最佳答案

您可以使用 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'

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

如果您想获得更多信息,例如进程 ID路径,整理输出需要更多的努力。

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 的输出是格式化为表格的文本。不幸的是,它返回的不仅仅是我们需要的应用程序,所以我们需要稍微整理一下。所有需要的应用程序都在描述 列中有一个条目,因此我们只检查第一个字符是否为空格。

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

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

关于python - 使用 python 获取正在运行的 Windows 应用程序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54827918/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com