我想只返回在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
的输出是文本格式化为表格。不幸的是,它返回的不仅仅是我们需要的应用程序,所以我们需要整理一下。所有需要的应用程序在Description列中都有一个条目,因此我们只检查第一个字符是否为空格。
这就是原始表的样子(在isspace()
if子句之前):
Description Id Path
----------- -- ----
912
9124
11084
Microsoft Office Excel 1944 C:\Program Files (x86)\Microsoft Office\Office12\EXCEL.EXE