pythonstringinputeof

How to read user input until EOF?


My current code reads user input until line-break. But I am trying to change that to a format where the user can write input until they press Ctrl+D to end their input.

I currently do it like this:

input = raw_input ("Input: ")

But how can I change that to an EOF-ready version?


Solution

  • Use file.read:

    input_str = sys.stdin.read()
    

    According to the documentation:

    file.read([size])

    Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached.

    >>> import sys
    >>> isinstance(sys.stdin, file)
    True
    

    BTW, dont' use input as a variable name. It shadows builtin function input.