Search code examples
pythoninputstdineof

Problem when reading values from console using stdin.read()


I have this part of python code that should read input values from the screen. When it runs, it keeps running forever. I tried CTRL+D as per the search results, but it does not work. This code is given and it works when I submit the code to an online grader but does not work on my windows machine.

if __name__ == "__main__":
    data = list(map(int, sys.stdin.read().split()))
    n, capacity = data[0:2]
    values = data[2:(2 * n + 2):2]
    weights = data[3:(2 * n + 2):2]

    opt_value = get_optimal_value(capacity, weights, values)

    print("{:.10f}".format(opt_value))

Sample input should be:

3 2
20 50 
12 12
51 51

Solution

  • On Windows you should use Ctrl-Z instead of Ctrl-D. Also, this should be the first character of a newline, and there should be a newline (enter) after the Ctrl-Z as well. There may be other characters after the Ctrl-Z, which will be ignored.

    So, the shortest sequence to force an EOL on Windows is: Enter, Ctrl-Z, Enter.

    I know this from experience and did found some answers or comments stating the same, but I couldn't find any official documentation where this is explained. If I find it, I will add it to this answer.

    (please leave a comment if you know a reliable source for this behaviour.)