0

im trying to get the memory usage of the python process itself through a python script with python standard library with win7 64. I searched for a solution and got to : http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/

def memory_usage_ps():
import subprocess
out = subprocess.Popen(['ps', 'v', '-p', str(os.getpid())],
stdout=subprocess.PIPE).communicate()[0].split(b'\n')
vsz_index = out[0].split().index(b'RSS')
mem = float(out[1].split()[vsz_index]) / 1024
return mem

usage of the given function gives me error code:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
    exec codeObject in __main__.__dict__
  File "C:\Users\..\Desktop\Script3.py", line 10, in <module>
    memory_usage_ps()
  File "C:\Users\..\Desktop\Script3.py", line 4, in memory_usage_ps
    out = subprocess.Popen(['ps', 'v', '-p', str(os.getpid())], stdout=subprocess.PIPE).communicate()[0].split(b'\n')
  File "C:\Program Files (x86)\Python27\lib\subprocess.py", line 710, in __init__
    errread, errwrite)
  File "C:\Program Files (x86)\Python27\lib\subprocess.py", line 958, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

would appreciate some advice...

rix
  • 93
  • 8

2 Answers2

0

The problem is that the script example if Unix-specific. You cannot use in in Windows. What you need is to browse through the Windows APIs to see what function allows you to get the memory use of a process. How to use Windows APIs from Python has been well-explained here previously, see e.g. How to use win32 API's with python?

The Win32 API function you may want to use is GetProcessMemoryInfo: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683219(v=vs.85).aspx

Community
  • 1
  • 1
juhist
  • 4,210
  • 16
  • 33
0

thanks. my new code seems to work...

import win32api
import os
from win32process import GetProcessMemoryInfo
from win32con import PROCESS_QUERY_INFORMATION, PROCESS_VM_READ
import win32com.client

wmi=win32com.client.GetObject('winmgmts:')
for p in wmi.InstancesOf('win32_process'):
    if p.Name == "python.exe":
        handle = win32api.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, p.Properties_('ProcessId'))
        memoryUsage = GetProcessMemoryInfo(handle)
        print memoryUsage['WorkingSetSize']
rix
  • 93
  • 8