Today I learned you can read from stdin with open(0).

The code `open(0)  # ?!` in a good-looking thumbnail.

Opening a file

In Python, we typically use the function open to open a file and read from it. In particular, the construct

with open(filepath, mode) as f:
    ...

is very common in Python.

Well, today I learned that the function open can accept the integer 0 to read from standard input.

That's because the function open accepts file descriptors as its argument, and 0 is the file descriptor for standard input.

1 is the file descriptor for standard output, and 2 is the file descriptor for standard error, so you can also write to these two streams by using the built-in open:

>>> stdout.write("Hello, world!\n")
Hello, world!
14
>>> stdout.close()

Knowing that you can read from stdin with open(0), you can type in multiline input in the REPL with ease:

>>> msg = open(0).read()
Hello,
world!
^Z
>>> msg
'Hello,\nworld!\n'

To stop reading, you need to go to an empty new line and press some magic key(s). (On Windows, it's Ctrl+Z. On Linux/Mac OS it may be Ctrl+D, not sure.)

That's it for now! Stay tuned and I'll see you around!

Become a better Python 🐍 developer πŸš€

+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!

My book β€œPydon'ts” teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here πŸπŸš€.

Previous Post Next Post

Blog Comments powered by Disqus.