1

I found some code which inputs data like so:

n, *b = open(0)

The input is a bunch of lines of numbers, so presumably the first line should be saved to n and the rest of the lines saved to b.

How exactly do you input the lines using stdin? For example, I open the conda terminal and type python test.py and hit enter. Then I copy the text into the terminal and hit enter but nothing happens. What exactly is the format required if you have a text file with lines of numbers, to input these lines and save them into the n and b variables using open(0)?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
jimbo
  • 11
  • 1
  • 2
    `python test.py < textFileWithLinesOfNumbers.txt` perhaps. If you pasted the text into the running Python program, you'd have to explicitly indicate an End-Of-File (Ctrl-D or Ctrl-Z) to terminate the input. – jasonharper Dec 12 '21 at 02:10
  • 3
    My guess is they have defined their own `open` function that hides the Python builtin. I don't know of any conditions under which `open` returns multiple values. – Tim Roberts Dec 12 '21 at 02:18

1 Answers1

1

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153