Python3:Reportlab图像 – ResourceWarning:未闭合的文件

当我运行单元测试时,我在以下代码中的“徽标”图像上获得了Python 3未闭合的缓冲区错误.如何正确关闭徽标图像缓冲区?请注意,Image类来自reportlab.platypus.

我已经尝试过logo.close()和使用Image(logo_path)作为徽标:,它们都不起作用.

>>python -m unittest tests.test_sample_pdf

>>/tests/test_sample_pdf.py:51: ResourceWarning: unclosed file <_io.BufferedReader name='/Users/my_prj/statics/my-logo.gif'>
      get_pdf()

源代码

import unittest
import os
from io import BytesIO
from os.path import abspath, dirname
from reportlab.lib.colors import HexColor
from reportlab.lib.enums import TA_RIGHT
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch, cm, mm
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, BaseDocTemplate, Paragraph, Image, Spacer


COL_SORT = [{"headerName": "name",
             "field": "name",
             "width": 1000,}]

def get_pdf():
    # setup PDF template
    buffer = BytesIO()
    side_margin = 12
    col_widths = [row['width'] for row in COL_SORT]
    page_width = sum(col_widths) + side_margin * 3
    pdf = SimpleDocTemplate(buffer, pagesize=(page_width, 8.5 * inch), rightMargin=side_margin, leftMargin=side_margin,
                            topMargin=side_margin, bottomMargin=side_margin)
    elements = []

    # logo
    parent_dir = dirname(dirname(abspath(__file__)))
    logo_path = os.path.join(parent_dir, 'statics', 'my-logo.gif')
    logo = Image(logo_path)
    logo.hAlign = 'LEFT'

    heading_style = ParagraphStyle(name='heading', fontSize=16, leading=20, spaceAfter=0,
                                   textColor=HexColor('#ffffff'), backColor=HexColor('#465a81'))
    heading_right_style = ParagraphStyle(name='heading', fontSize=16, leading=20, spaceAfter=0,
                                         textColor=HexColor('#ffffff'), backColor=HexColor('#465a81'),
                                         alignment=TA_RIGHT)
    logo_tbl = Table([[logo]], colWidths=sum(col_widths))
    logo_tbl.hAlign = 'LEFT'
    logo_tbl.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), HexColor('#B90002'))]))
    elements.append(logo_tbl)

    # build PDF
    pdf.build(elements)
    pdf_string = buffer.getvalue()
    buffer.close()

class TestPDF(unittest.TestCase):
    def test_pdf(self):
        get_pdf()

解决方法:

看来reportlab希望你打开和关闭图像文件.与open(logo_path,’rb’)一起使用作为image_fd:.

此解决方法解决了警告.我已经添加了提到的并缩进了以下行.

def get_pdf():
    # setup PDF template
    buffer = BytesIO()
    side_margin = 12
    col_widths = [row['width'] for row in COL_SORT]
    page_width = sum(col_widths) + side_margin * 3
    pdf = SimpleDocTemplate(buffer, pagesize=(page_width, 8.5 * inch), rightMargin=side_margin, leftMargin=side_margin,
                            topMargin=side_margin, bottomMargin=side_margin)
    elements = []

    # logo
    parent_dir = dirname(dirname(abspath(__file__)))
    logo_path = os.path.join(parent_dir, 'statics', 'nci-logo.gif')
    with open(logo_path, 'rb') as image_fd:            # edited this line
        logo = Image(image_fd)                         # ... and this line
        logo.hAlign = 'LEFT'

        heading_style = ParagraphStyle(name='heading', fontSize=16, leading=20, spaceAfter=0,
                                   textColor=HexColor('#ffffff'), backColor=HexColor('#465a81'))
        heading_right_style = ParagraphStyle(name='heading', fontSize=16, leading=20, spaceAfter=0,
                                         textColor=HexColor('#ffffff'), backColor=HexColor('#465a81'),
                                         alignment=TA_RIGHT)
        logo_tbl = Table([[logo]], colWidths=sum(col_widths))
        logo_tbl.hAlign = 'LEFT'
        logo_tbl.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), HexColor('#B90002'))]))
        elements.append(logo_tbl)

        # build PDF
        pdf.build(elements)
        pdf_string = buffer.getvalue()
        buffer.close()

输出:

$python -m unittest tests.test_sample_pdf
.
----------------------------------------------------------------------
Ran 1 test in 0.042s

OK

我把完整的例子放在Github

上一篇:python – 如何使用报告实验室将PDF添加到PDF


下一篇:〖教程〗Ladon检测100种网络摄像头默认密码列表