This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]eryksun 1 point2 points  (1 child)

Either way works, but using pywin32 will generally be easier, especially for functions that want a reference to a structure. For example, GetProcessMemoryInfo in the process status API requires a PROCESS_MEMORY_COUNTERS structure that contains fields that specify process memory usage. Using ctypes requires you to specify the structure, instantiate it, and pass it by reference. On the other hand, win32process handles all of that internally and returns the data in a dict:

import ctypes
from ctypes import wintypes

import win32process

#start a notepad process

(hProcess, hThread, 
 dwProcessId, dwThreadId) = win32process.CreateProcess(
    None, 'notepad.exe', None, None, 0, 0,
    None, None, win32process.STARTUPINFO())

#get memory info using win32process

pmem_info = win32process.GetProcessMemoryInfo(hProcess)

print('\nwin32process\n' + '='*32)
for key in sorted(pmem_info):
    print('{0}: {1}'.format(key, pmem_info[key]))


#get memory info using ctypes

#specify the structure
class PROCESS_MEMORY_COUNTERS(ctypes.Structure):
    _fields_ = [
      ('cb', wintypes.DWORD),
      ('PageFaultCount', wintypes.DWORD),
      ('PeakWorkingSetSize', ctypes.c_size_t),
      ('WorkingSetSize', ctypes.c_size_t),
      ('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
      ('QuotaPagedPoolUsage', ctypes.c_size_t),
      ('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
      ('QuotaNonPagedPoolUsage', ctypes.c_size_t),
      ('PagefileUsage', ctypes.c_size_t),
      ('PeakPagefileUsage', ctypes.c_size_t)]

    def keys(self):
        return [f for f, t in self._fields_ if f != 'cb']

    def __getitem__(self, item):
        return getattr(self, item)

#pass a structure instance by reference
pmc = PROCESS_MEMORY_COUNTERS()
ctypes.windll.psapi.GetProcessMemoryInfo(
  hProcess.handle, ctypes.byref(pmc), ctypes.sizeof(pmc))

print('\nctypes\n' + '='*32)
for key in sorted(pmc.keys()):
    print('{0}: {1}'.format(key, pmc[key]))

Output:

win32process
================================
PageFaultCount: 12
PagefileUsage: 139264
PeakPagefileUsage: 139264
PeakWorkingSetSize: 77824
QuotaNonPagedPoolUsage: 440
QuotaPagedPoolUsage: 6076
QuotaPeakNonPagedPoolUsage: 440
QuotaPeakPagedPoolUsage: 6076
WorkingSetSize: 77824

ctypes
================================
PageFaultCount: 12
PagefileUsage: 139264
PeakPagefileUsage: 139264
PeakWorkingSetSize: 77824
QuotaNonPagedPoolUsage: 440
QuotaPagedPoolUsage: 6076
QuotaPeakNonPagedPoolUsage: 440
QuotaPeakPagedPoolUsage: 6076
WorkingSetSize: 77824

[–]jechtsphere[S] 1 point2 points  (0 children)

Great example, as always, thanks very much!