File: memory.py

package info (click to toggle)
python-scrapy 0.8-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 2,904 kB
  • ctags: 2,981
  • sloc: python: 15,349; xml: 199; makefile: 68; sql: 64; sh: 34
file content (25 lines) | stat: -rw-r--r-- 826 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import os

_vmvalue_scale = {'kB': 1024, 'mB': 1024*1024, 'KB': 1024, 'MB': 1024*1024}

def get_vmvalue_from_procfs(vmkey='VmSize', pid=None):
    """Return virtual memory value (in bytes) for the given pid using the /proc
    filesystem. If pid is not given, it default to the current process pid.
    Available keys are: VmSize, VmRSS (default), VmStk
    """
    if pid is None:
        pid = os.getpid()
    try:
        t = open('/proc/%d/status' % pid)
    except IOError:
        raise RuntimeError("/proc filesystem not supported")
    v = t.read()
    t.close()
    # get vmkey line e.g. 'VmRSS:  9999  kB\n ...'
    i = v.index(vmkey + ':')
    v = v[i:].split(None, 3)  # whitespace
    if len(v) < 3:
        return 0  # invalid format?
    # convert Vm value to bytes
    return int(v[1]) * _vmvalue_scale[v[2]]