Contrary to the other answer, the code in question works. I tested it.
open(0)
creates a file object that represents the standard input (unless you have remapped the file descriptors first). A file is iterable; iterating over it gives the lines of the file. Writing something like n, *b =
unpacks the right-hand side; this entails iterating over it.
To provide the input by typing it in at the terminal, therefore: each value should be on a separate line; and the end of file needs to be indicated by using Ctrl+D on Linux/Mac or Ctrl+Z on Windows.
Seeing it in action:
$ echo 'n, *b = open(0); print(n, b)' > bizarre.py
$ python bizarre.py
1
2
3
1
['2\n', '3\n']
The 1
, 2
and 3
are input by me; then I use Ctrl+D to indicate the end of input. That stops the iteration so that the unpacking can complete and the rest of the program can proceed; the 1
and the list are output from the program. (There is a space before the list because that is the default sep
for print
; the values are on separate lines because n
is actually equal to the string '1\n'
.)
Alternately, you can redirect data from a file:
$ cat > data.txt
1
2
3
$ python bizarre.py < data.txt
1
['2\n', '3\n']
Here I simply used cat
to create the text file for a self-contained example; but you can produce it by any method. We use the terminal to redirect the file to Python's standard input. Since it's now reading from a file, there is already an end-of-file and we don't need any more babysitting.