Read user Input until EOF in Python


Borislav Hadzhiev

Last updated: Aug 24, 2022


Photo from Unsplash

Read user Input until EOF in Python #

Use the sys.stdin.readlines() method to read user input until EOF. The readlines() method will return a list containing the lines. The user can press CTRL + D (Unix) or CTRL + Z (Windows) to exit.
import sys # 👇️ User must press Ctrl + D (Unix) or Ctrl + Z (Windows) to exit print('Press CTRL + D (Unix) or CTRL + Z (Windows) to exit') user_input = sys.stdin.readlines() # 👇️ get list of lines print(user_input) # 👇️ join the list items into a string print(''.join(user_input))

read input until eof

stdin is used for interactive user input.

The user must press CTRL + D (on Unix) or CTRL + Z on Windows to exit.

The readlines() method returns a list containing the list the user entered.

You can use the str.join() method if you need to join the list of strings into a string.
# a # b # c print(''.join(['a\n', 'b\n', 'c\n']))

If you only need a string containing the lines, use the method instead.
import sys user_input = print(user_input)

read input until eof stdin read

The method returns a string containing the lines the user entered.

Alternatively, you can use a try/except statement.

To read user input until EOF:

  1. Use a while loop to iterate until EOF.
  2. On each iteration, append the user input to a list.
  3. Catch the EOFError exception in the except block and break out of the loop.
lines = [] while True: try: lines.append(input()) except EOFError: lines_str = '\n'.join(lines) print(lines_str) break print(lines)

read user input until eof try except

We used a while loop to iterate until EOF.

If the user presses CTRL + D (Unix) or CTRL + Z (Windows), an EOFError exception is raised and is handled in the except block.

The break statement breaks out of the innermost enclosing for or while loop.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.