Getting total/free RAM from within Python

后端 未结 5 1708
被撕碎了的回忆
被撕碎了的回忆 2021-02-08 15:59

From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way?

Ideally, the amount

相关标签:
5条回答
  • 2021-02-08 16:22

    Have you tried SIGAR - System Information Gatherer And Reporter? After install

    import os, sigar
    
    sg = sigar.open()
    mem = sg.mem()
    sg.close() 
    print mem.total() / 1024, mem.free() / 1024
    

    Hope this helps

    0 讨论(0)
  • 2021-02-08 16:22

    You can't do this with just the standard Python library, although there might be some third party package that does it. Barring that, you can use the os package to determine which operating system you're on and use that information to acquire the info you want for that system (and encapsulate that into a single cross-platform function).

    0 讨论(0)
  • 2021-02-08 16:31

    In windows I use this method. It's kinda hacky but it works using standard os library:

    import os
    process = os.popen('wmic memorychip get capacity')
    result = process.read()
    process.close()
    totalMem = 0
    for m in result.split("  \r\n")[1:-1]:
        totalMem += int(m)
    print totalMem / (1024**3)
    
    0 讨论(0)
  • 2021-02-08 16:32

    For the free memory part, there is a function in the wx library:

    wx.GetFreeMemory()
    

    Unfortunately, this only works on Windows. Linux and Mac ports either return "-1" or raise a NotImplementedError.

    0 讨论(0)
  • 2021-02-08 16:33

    psutil would be another good choice. It also needs a library installed however.

    >>> import psutil
    >>> psutil.virtual_memory()
    vmem(total=8374149120L, available=2081050624L, percent=75.1,
         used=8074080256L, free=300068864L, active=3294920704,
         inactive=1361616896, buffers=529895424L, cached=1251086336)
    
    0 讨论(0)
提交回复
热议问题