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!

I hope you learned something new! If you did, consider following the footsteps of the readers who bought me a slice of pizza 🍕. Your small contribution helps me produce this content for free and without spamming you with annoying ads.

Previous Post Next Post

Blog Comments powered by Disqus.