Planet Python

Rodrigo Girão Serrão: TIL #139 – Multiline input in the REPL

The text explains a method for achieving multiline input within a Python Read-Eval-Print Loop (REPL). Standard input can be accessed using `open(0)`, enabling multiline input using Ctrl+D (Unix) or Ctrl+Z (Windows) for EOF. The initial use of `open(0).read()` successfully captures multiline input as a string. However, subsequent attempts to read from standard input in this manner result in an `OSError`. This error occurs because Python closes the file descriptor after the first read operation. The solution lies in the `closefd=False` argument within the `open()` function. By setting `closefd=False`, the file descriptor remains open after reading. This allows for repeated reading of multiline input from standard input within the REPL environment. Sequential calls of `open(0, closefd=False).read()` then work without issue. This technique enables continued multiline input within the REPL session. The primary advantage is facilitating interactive code testing with multiline data.
favicon
mathspp.com
mathspp.com
Image for the article: Rodrigo Girão Serrão: TIL #139 – Multiline input in the REPL