简体   繁体   English

Python3:Reportlab图像 - ResourceWarning:未闭合文件<_io.BufferedReader name = ...>

[英]Python3: Reportlab Image - ResourceWarning: unclosed file <_io.BufferedReader name=…>

When I run a unit test, I'm getting Python 3 unclosed buffer error on the "logo" image in the following code. 当我运行单元测试时,我在以下代码中的“徽标”图像上获得了Python 3未闭合的缓冲区错误。 How do I close the logo image buffer correctly? 如何正确关闭徽标图像缓冲区? Please be aware that the Image class is coming from reportlab.platypus . 请注意, Image类来自reportlab.platypus

I have tried logo.close() and with Image(logo_path) as logo: , both of them does not work. 我已经尝试过logo.close()with Image(logo_path) as logo: ,它们都不起作用。

>>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()

Source Code 源代码

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()

It seems that reportlab expects that you open and close the image file. 看来reportlab希望打开和关闭图像文件。 Use with open(logo_path, 'rb') as image_fd: . with open(logo_path, 'rb') as image_fd: .

This workaround solves the Warning. 此解决方法解决了警告。 I've added the mentioned with and indented its following lines. 我已经添加了提到with并缩进了以下行。

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()

Output: 输出:

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

OK

I've put the complete example in Github 我把完整的例子放在Github中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ResourceWarning:未关闭的文件 &lt;_io.BufferedReader name=4&gt; - ResourceWarning: unclosed file <_io.BufferedReader name=4> Python 3:ResourceWarning:unclosed文件<_io.TextIOWrapper name ='PATH_OF_FILE' - Python 3: ResourceWarning: unclosed file <_io.TextIOWrapper name='PATH_OF_FILE' 莫名其妙的ResourceWarning:未关闭的文件&lt;_io.TextIOWrapper名称= 3 - Inexplicable ResourceWarning: unclosed file <_io.TextIOWrapper name=3 尝试在 Python 中使用 matplotlib 保存图形动画 - “无效的文件对象:&lt;_io.BufferedReader name=76&gt;” - Trying to save an animated of graph with matplotlib in Python - "Invalid file object: <_io.BufferedReader name=76>" 从Python io.BufferedReader类的实例读取/打开图像 - Read/Open image from instance of Python io.BufferedReader class 使用Python 3中的io.BufferedReader快速读取gzip(文本文件) - Fast reading of gzip (text file) using io.BufferedReader in Python 3 Python - 使用 _io.BufferedReader 获取 TypeError - Python - Getting TypeError with _io.BufferedReader 致命的 Python 错误:在解释器关闭时无法获取 &lt;_io.BufferedReader name=8&gt; 的锁定,可能是由于守护线程 - Fatal Python error: could not acquire lock for <_io.BufferedReader name=8> at interpreter shutdown, possibly due to daemon threads 浏览文件Tkinter后在&lt;_io.BufferedReader name =&#39;Path&#39;&gt;中恢复路径 - Recover Path in <_io.BufferedReader name='Path'> after browsing a file Tkinter python-gnupg的verify_file不喜欢我将它传递给_io.BufferedReader - python-gnupg's verify_file doesn't like me passing it an _io.BufferedReader
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM