prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.1k stars 717 forks source link

Fix ValueError: I/O operation on closed file. #1878

Closed tchalupnik closed 3 weeks ago

tchalupnik commented 3 weeks ago

Hello Jonathan!

I found such a problem:

from prompt_toolkit import print_formatted_text
from pytest import CaptureFixture

def test_1(capsys: CaptureFixture[str]) -> None:
    print_formatted_text("TEST")

def test_2() -> None:
    print_formatted_text("TEST")

that ends up with:

py/lib/python3.11/site-packages/prompt_toolkit/shortcuts/utils.py:164: in print_formatted_text
    render()
py/lib/python3.11/site-packages/prompt_toolkit/shortcuts/utils.py:139: in render
    renderer_print_formatted_text(
py/lib/python3.11/site-packages/prompt_toolkit/renderer.py:813: in print_formatted_text
    output.flush()
py/lib/python3.11/site-packages/prompt_toolkit/output/plain_text.py:59: in flush
    flush_stdout(self.stdout, data)
py/lib/python3.11/site-packages/prompt_toolkit/output/flush_stdout.py:33: ValueError
ValueError: I/O operation on closed file.

CaptureFixture closes the output stdout so I added checks they prevent such a case

tchalupnik commented 3 weeks ago

Closing as we were able to work out the better way to make Capsys pytest's feature compatible in #1880