我正在使用python 2.7和windows。我想找出进程名称时活动的进程ID列表。
import time
import win32pdh
def GetProcessID( name ) :
object = "Process"
items, instances = win32pdh.EnumObjectItems( None, None, object,
win32pdh.PERF_DETAIL_WIZARD )
val = None
if name in instances :
hq = win32pdh.OpenQuery()
hcs = [ ]
item = "ID Process"
path = win32pdh.MakeCounterPath( ( None, object, name, None, 0, item ) )
hcs.append( win32pdh.AddCounter( hq, path ) )
win32pdh.CollectQueryData( hq )
time.sleep( 0.01 )
win32pdh.CollectQueryData( hq )
for hc in hcs:
type, val = win32pdh.GetFormattedCounterValue( hc, win32pdh.PDH_FMT_LONG )
win32pdh.RemoveCounter( hc )
win32pdh.CloseQuery( hq )
return val
hh=GetProcessID("python")
在上面的代码中,即使两个python进程正在运行,我也只获得了一个进程ID。我的查询如何使用python进程激活所有进程ID
答案 0 :(得分:0)
您可以使用psutil获取此信息:
import psutil
NoNameAccesses = []
for p in psutil.process_iter():
try:
if p.name.startswith('python'):
print (p.name, p.pid)
except psutil._error.AccessDenied:
# Handle where the user does not have permission to get the name
NoNameAccesses.append(p.pid)
if len(NoNameAccesses) > 0:
print ("Warning: You don't have access to he following processes:")
print (NoNameAccesses)
更正了感谢Bakuriu的评论
答案 1 :(得分:0)
您可以尝试调用“tasklist”并处理输出。
中描述为答案