内存泄漏/ Python windows 7截图

我在双监视器系统(
Windows7)上尝试了以下
Python代码,以反复保存屏幕截图.

它产生33个14.6MB(总共482MB)的镜头然后崩溃.使用Process Explorer检查我可以看到已用内存量增加到大约500MB.

我的问题是如何阻止内存泄漏?

import win32gui, win32ui, win32con, win32api
import time
import os


def my_capture(file_name):
    hwin = win32gui.GetDesktopWindow()
    width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
    height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
    left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
    top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
    hwindc = win32gui.GetWindowDC(hwin)
    srcdc = win32ui.CreateDCFromHandle(hwindc)
    memdc = srcdc.CreateCompatibleDC()
    bmp = win32ui.CreateBitmap()    
    bmp.CreateCompatibleBitmap(srcdc, width, height)
    memdc.SelectObject(bmp)
    memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)
    bmp.SaveBitmapFile(memdc, file_name) # 'screenshot.bmp'


def captureAndSave(i):
    if i < 10:
        tmpStr = "00000" + str(i)
    elif i < 100:
        tmpStr = "0000" + str(i)
    elif i < 1000:
        tmpStr = "000" + str(i)
    elif i < 10000:
        tmpStr = "00" + str(i)
    elif i < 100000:
        tmpStr = "0" + str(i)
    else:
        tmpStr = str(i)

    my_capture(tmpStr + '.bmp')


def myMainLoop():
    i = 0
    while 1:
        i = i + 1
        captureAndSave(i)
        time.sleep(0.2)

#-----------------------------------------------------------------------------

if __name__ == '__main__':
    try:
        myMainLoop()        # capure all monitor windows
    except KeyboardInterrupt:
        pass 

我从Python windows 7 screenshot without PIL得到了基本代码:

最佳答案 您需要清理位图和DC,在保存位图后添加类似的内容;

win32gui.DeleteObject(bmp.GetHandle())
memdc.DeleteDC()
srcdc.DeleteDC()
win32gui.ReleaseDC(hwin, hwindc) 
点赞