for f in Path(filedir).glob(filename_formate+'*.jpg'): try: image = Image.open(f)…
- User
for f in Path(_file_dir).glob(_file_name_formate+'.jpg'): try: image = Image.open(f) _image_width,_image_height = image.size if _image_width > 30 and _image_height >30: _pdf_jpg_images_files_count = _pdf_jpg_images_files_count + 1 # f.unlink() except OSError as e: print("Error: %s : %s" % (f, e.strerror)) for f in Path(_file_dir).glob(_file_name_formate+'.p*m'): try: image = Image.open(f) _image_width, _image_height = image.size if _image_width > 30 and _image_height > 30: _pdf_pdm_images_files_count = _pdf_pdm_images_files_count + 1 # f.unlink() except OSError as e: print("Error: %s : %s" % (f, e.strerror)) 上边代码会不会有造成内存泄漏?如果修改
- Assistant
你这段代码的主要功能是遍历指定目录下符合特定格式的图片文件(jpg和某种带p*m格式的文件),然后用PIL的
Image.open()打开图片获取尺寸,再根据条件统计计数。会不会造成内存泄漏?
理论上单次循环调用
Image.open()并不会造成内存泄漏,Python 的垃圾回收机制会释放不再使用的对象。但
PIL.Image.open()返回的Image对象其实是文件的一个打开句柄(资源),如果不显式关闭文件,有可能造成打开文件句柄泄漏,从而影响程序的文件描述符资源。这个“资源泄漏”从严格意义上说也算内存泄漏的一种表现,但更精确是资源泄漏。所以你的代码没有显式关闭打开的图像会存在资源占用风险,尤其当文件数很多时,程序可能打开太多文件句柄,导致打开失败。
如何改进避免资源泄漏?
推荐的方法:
- 使用
with上下文管理器来打开图片,确保打开文件会自动关闭 - 或者显示调用
image.close()确保手动释放
你的代码修改示例:
python - 使用
- User
subprocess.call( ['/usr/local/bin/pdfimages', '-j', '-f', '1', '-l','-1', full_file_loc,pdfimages_temp_dir]) 这个代码,会产生占用内存的情况吗?
- Assistant
你这段代码:
pythonsubprocess.call( ['/usr/local/bin/pdfimages', '-j', '-f', '1', '-l', '-1', full_file_loc, pdfimages_temp_dir])调用了外部程序
pdfimages来处理PDF文件,参数是从第1页到最后一页(-l -1),并将结果存储到指定的临时目录。
是否会产生占用内存的情况?
-
外部程序占用内存
subprocess.call()是阻塞调用,会启动pdfimages这个命令行程序作为子进程。
pdfimages程序本身会根据PDF的大小和复杂度,占用一定的系统内存来解析和提取图片。
这个内存占用是正常的,只要程序在运行,都会占用一定内存。 -
Python端是否会产生额外内存占用
你的Python代码只是启动外部程序,并等待其完成。不会把外部程序的输出缓存到Python内存中(除非你用并额外处理流)。因此,Python脚本本身在这段代码执行时占用内存通常。
-
- User
pdfimages进程消耗的内存,在执行完会释放内存吗?
- Assistant
是的,
pdfimages进程在执行完成后会释放它所占用的所有内存资源。具体说明:
pdfimages是一个独立的操作系统进程,当你通过subprocess.call()或类似方式启动它时,操作系统会为该进程分配所需的内存和资源。- 当
pdfimages执行完毕并正常退出时,操作系统会自动回收这个进程占用的所有资源,包括内存、文件句柄等。 - 因此,
pdfimages进程本身不会在你调用它的 Python 程序中持续占用内存;它的内存使用生命周期仅限于该进程存在期间。 - 如果你发现在
pdfimages执行完之后内存没有被释放,极大可能是其他进程或系统缓存导致的,与pdfimages本身无关。
简单来说:
- 进程结束 => 操作系统释放内存。
- 不会因为调用
pdfimages让 Python 程序持续占用额外内存。
你只需要关注:
- 运行时
pdfimages的内存峰值是否过大,是否超出服务器承载能力。 - 确保
pdfimages没有异常崩溃卡住(这会导致进程不退出,内存不释放)。
如果你怀疑内存被“泄漏”,可以用这些命令排查:
bashps aux | grep pdfimages # 查看 pdfimages 进程状态 top # 观察进程实时内存占用 free -m # 查看系统内存使用情况
总结:
只要
pdfimages进程正常结束,内存都会被操作系统释放,不会造成内存泄漏。 - User
def extract_pdf_head_image(pdffile_path): ''' 提取头像图片返回头像图片路径 :return: image_bytes,image_ext ''' doc = fitz.open(pdffile_path) page = doc[0]#取第一页的头像 d = page.get_text("dict") blocks = d["blocks"] # the list of block dictionaries imgblocks = [b for b in blocks if b["type"] == 1] for imgblock in imgblocks: _bbox = imgblock['bbox'] # img_rect_height = _bbox x1,y1,x2,y2 = _bbox imgblockrect_height = abs(y2-y1) imgblockrect_width = abs(x2-x1) image_radio = imgblockrect_width / imgblockrect_height page_rect = page.rect if imgblockrect_width > 43 and imgblockrect_height > 43 and imgblockrect_width < page_rect.width/2
and imgblockrect_height < page_rect.height/3 and image_radio > 0.6 and image_radio < 1.2: #上边条件认为是人像照片条件 image_ext = imgblock['ext'] output_image_path = pdffile_path + '-head' + str(imgblock['number']) +'.' + image_ext #保存照片 imgdata = imgblock['image'] if len(imgdata) < 800: continue ofile = open(output_image_path, "wb") ofile.write(imgdata) ofile.close() imgdata = None print(f'找到头像照片{output_image_path}') return output_image_path doc.close() return None 上边代码会内存泄漏吗? - Assistant
你的代码是用
fitz(PyMuPDF)库从PDF第一页中提取符合条件的头像图片,并保存成文件。针对你的代码是否会造成内存泄漏,分析如下: