简体   繁体   English

使用Python获取Windows 8.1进程列表

[英]Get list of Windows 8.1 processes using Python

I want to get the list of processes in memory including the name and the PID in Windows 8.1. 我想获取内存中的进程列表,包括Windows 8.1中的名称和PID。

Here's my code: 这是我的代码:

import subprocess
import os

cmd = "WMIC PROCESS get Caption,ProcessId"
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
  # Additional logic here

The loop never runs. 循环永远不会运行。 This code worked in an earlier version of Windows 8. Is there a different approach someone can recommend? 此代码适用于早期版本的Windows 8.是否有人可以推荐不同的方法?

Instead of the cumbersome subprocess , you can use the fabolous, cross-platform psutil library. 您可以使用fabolous ,跨平台的psutil库,而不是繁琐的subprocess 进程

Using the general purpose psutil.process_iter() will allow you to do pretty much anything you'd like with the Process objects it returns (get name, pid, filter the ones you're interested in, etc.) 使用通用的psutil.process_iter()将允许你使用它返回的Process对象做任何你喜欢的事情(获取名称,pid,过滤你感兴趣的那些,等等)

Eg 例如

for proc in psutil.process_iter():
    print proc.pid, proc.name

Shx2, thank you for your response. Shx2,谢谢你的回复。 While your solution is better for multiplatform support, here's the solution I went with since I'm only running Windows 8.1. 虽然您的解决方案更适合多平台支持,但这是我使用的解决方案,因为我只运行Windows 8.1。

 from win32com.client import GetObject

 Wmi = GetObject('winmgmts:')
 processes = Wmi.InstancesOf('Win32_Process')

 # Get the Explorer process
 explorer = Wmi.ExecQuery('select * from Win32_Process where Name="explorer.exe"')

 # Grab its Pid
 processId = explorer[0].Properties_('ProcessId').Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM