Jeffrey Chen
Jeffrey Chen

Reputation: 23

Taking multiple lines of input in Python from the system.in

For one of my assignments, rather than reading directly from a text file, we are directly taking the input from sys.in. I was wondering what the best way of obtaining this input and storing it would be? So far, I've tried using:

sys.stdin.readlines() -- But this will not terminate unless it recieves an EOF statement, while a zero in my input signals the end of the file.

sys.stdin.readline() -- It will only read the final line of the input code.

input() -- I can only read in the first line of the input and when I try to loop it, I end up with a syntax error.

An example of the input is below:

3
2 1 3
3 2 1
1 3 2
2 1 3
3 2 1
1 3 2
2
1 2
1 2
2 1
2 1
0

My attempt at obtaining the input:

input_list = []

    while True:
        input_str = input("")
        if input_str == '0':
            break
        else:
            input_list.append(input_str)

    print(input_list)

Returns this error while parsing the second line through:

enter image description here

Any help with this would be greatly appreciated. I've probably spent longer trying to get the input to work now than the actual assignment now.

EDIT: The version of Python we are using is 3.4

FINAL EDIT: Like both the answers said, it turns out that the university labs have a older version of python running when run in cmd prompt in the labs, where the input() method started behaving differently. Once I tried the code at home, it worked as intended.

Upvotes: 2

Views: 1105

Answers (2)

mhawke
mhawke

Reputation: 87134

Avoid using input() as this behaves differently for different versions of Python. Instead, you can read from sys.stdin, this should work:

import sys

input_list = []

for line in sys.stdin:
    if line.strip() == '0':
        break
    input_list.append(line)
else:
    print('Warning: EOF occurred before "0" terminator')

print(input_list)

The for loop will terminate when a line with a single 0 is read, or when EOF is seen. The else lets you handle the case when the input terminates before 0 is seen; you can treat that as an error if that suits your application.

For your input, the output would be:

['3\n', '2 1 3\n', '3 2 1\n', '1 3 2\n', '2 1 3\n', '3 2 1\n', '1 3 2\n', '2\n', '1 2\n', '1 2\n', '2 1\n', '2 1\n']

Upvotes: 1

Anand S Kumar
Anand S Kumar

Reputation: 91009

For Python 2.x , you should use raw_input() .

In Python 2.x , using input() would actually try to evaluate the whatever was inputted, which can lead to issues (like the one you encountered) , and is dangerous (since it evaluates whatever the user inputs) .

raw_input() would not evaluate the inputted value, but would only return it as a string.

Upvotes: 1

Related Questions