python psutil替代_替代品psutil.过程(pid).nam

你提到这是windows版的。我看了一下psutil对windows的作用。看起来像psutil.过程()。name正在使用windows工具帮助API。如果您查看psutil的进程代码和trace.name,它将转到process_info.c中的get_name()。它会循环遍历系统上的所有pid,直到找到您要查找的pid。我认为这可能是toolhelpapi的一个限制。但这就是为什么它比.exe慢,后者使用不同的API路径(正如您所指出的那样)需要额外的特权。在

我想出的解决方案是使用ctypes和ctypes.windll直接调用windows ntapi。它只需要进程“查询”信息,这与进程“全部”访问不同:import ctypes

import os.path

# duplicate the UNICODE_STRING structure from the windows API

class UNICODE_STRING(ctypes.Structure):

_fields_ = [

('Length', ctypes.c_short),

('MaximumLength', ctypes.c_short),

('Buffer', ctypes.c_wchar_p)

]

# args

pid = 8000 # put your pid here

# define some constants; from windows API reference

MAX_TOTAL_PATH_CHARS = 32767

PROCESS_QUERY_INFORMATION = 0x0400

PROCESS_IMAGE_FILE_NAME = 27

# open handles

ntdll = ctypes.windll.LoadLibrary('ntdll.dll')

process = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION,

False, pid)

# allocate memory

buflen = (((MAX_TOTAL_PATH_CHARS + 1) * ctypes.sizeof(ctypes.c_wchar)) +

ctypes.sizeof(UNICODE_STRING))

buffer = ctypes.c_char_p(' ' * buflen)

# query process image filename and parse for process "name"

ntdll.NtQueryInformationProcess(process, PROCESS_IMAGE_FILE_NAME, buffer,

buflen, None)

pustr = ctypes.cast(buffer, ctypes.POINTER(UNICODE_STRING))

print os.path.split(pustr.contents.Buffer)[-1]

# cleanup

ctypes.windll.kernel32.CloseHandle(process)

ctypes.windll.kernel32.FreeLibrary(ntdll._handle)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值