我在双显示器系统(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
我的基本代码来自:没有 PIL 的 Python windows 7 screenshot: