您可以使用 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 id 或path,整理输出需要更多的努力。
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