使用 Python 获取 Windows 中计算机的内存使用情况

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2017545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:34:37  来源:igfitidea点击:

Get memory usage of computer in Windows with Python

pythonmemorywinapimemory-managementpywin32

提问by Claudiu

How can I tell what the computer's overall memory usage is from Python, running on Windows XP?

如何从运行在 Windows XP 上的 Python 判断计算机的总体内存使用情况?

采纳答案by Michael Greene

You'll want to use the wmimodule. Something like this:

您将需要使用wmi模块。像这样的东西:

import wmi
comp = wmi.WMI()

for i in comp.Win32_ComputerSystem():
   print i.TotalPhysicalMemory, "bytes of physical memory"

for os in comp.Win32_OperatingSystem():
   print os.FreePhysicalMemory, "bytes of available memory"

回答by Seth

You can also just call GlobalMemoryStatusEx() (or any other kernel32 or user32 export) directly from python:

您也可以直接从 python 调用 GlobalMemoryStatusEx() (或任何其他 kernel32 或 user32 导出):

import ctypes

class MEMORYSTATUSEX(ctypes.Structure):
    _fields_ = [
        ("dwLength", ctypes.c_ulong),
        ("dwMemoryLoad", ctypes.c_ulong),
        ("ullTotalPhys", ctypes.c_ulonglong),
        ("ullAvailPhys", ctypes.c_ulonglong),
        ("ullTotalPageFile", ctypes.c_ulonglong),
        ("ullAvailPageFile", ctypes.c_ulonglong),
        ("ullTotalVirtual", ctypes.c_ulonglong),
        ("ullAvailVirtual", ctypes.c_ulonglong),
        ("sullAvailExtendedVirtual", ctypes.c_ulonglong),
    ]

    def __init__(self):
        # have to initialize this to the size of MEMORYSTATUSEX
        self.dwLength = ctypes.sizeof(self)
        super(MEMORYSTATUSEX, self).__init__()

stat = MEMORYSTATUSEX()
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))

print("MemoryLoad: %d%%" % (stat.dwMemoryLoad))

Not necessarily as useful as WMI in this case, but definitely a nice trick to have in your back pocket.

在这种情况下不一定像 WMI 那样有用,但绝对是一个可以放在你的后兜里的好技巧。

回答by Skurmedel

You can query the performance counters in WMI. I've done something similar but with disk space instead.

您可以在 WMI 中查询性能计数器。我做了类似的事情,但用磁盘空间代替。

A very useful link is the Python WMI Tutorial by Tim Golden.

一个非常有用的链接是Tim GoldenPython WMI 教程