Skip to content

ImageGrab.grabclipboard() keeps unnecessary temporary files around #7147

@stephen-huan

Description

@stephen-huan

What did you do?

Call PIL.ImageGrab.grabclipboard() repeatedly.

What did you expect to happen?

A constant number of temp files to be created.

What actually happened?

The number of files in /tmp keeps increasing.

If there not an actual image in the clipboard, e.g. only text, then

xclip -selection clipboard -target image/png -out

will error with the message

Error: target image/png not available

while this error is caught on the latest Pillow (lines 146--148), the newly created tempfile is never removed.

Pillow/src/PIL/ImageGrab.py

Lines 146 to 151 in ab3d0c0

if err:
msg = f"{args[0]} error: {err.strip().decode()}"
raise ChildProcessError(msg)
im = Image.open(filepath)
im.load()
os.unlink(filepath)

This can cause tempfiles to accumulate with repeated calls of grabclipboard().

I think os.unlink(filepath) should be called before ChildProcessError is raised to remove the now unnecessary file, i.e.

        if err:
            os.unlink(filepath)
            msg = f"{args[0]} error: {err.strip().decode()}"
            raise ChildProcessError(msg)
        im = Image.open(filepath)
        im.load()
        os.unlink(filepath)

What are your OS, Python and Pillow versions?

  • OS: archlinux
  • Python: 3.11.3
  • Pillow: 9.5.0 (or commit ab3d0c0)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions