What's wrong with raw_input() (EOFError: EOF when reading a line)

14,276

Solution 1

You could use:

sys.stdin = open('/dev/tty')
answer = raw_input('Commit anyway? [N/y] ')

source: https://stackoverflow.com/a/7437724/1465640

Solution 2

This answer

sys.stdin = open('/dev/tty')
answer = raw_input('Commit anyway? [N/y] ')

is useful if you've previously read from sys.stdin in your code. In that case, the raw_input line will throw the EOF error without waiting for user input, if you set the sys.stdin = open('/dev/tty') just before raw_input, it resets the stdin and allows the user input to work. (tested in python 2.7) with

## test.py
import sys
for line in sys.stdin:
  pass
#sys.stdin = open('/dev/tty')
raw_input("Are you sure?")

echo 'abc' | python test.py

Which raises:

EOFError: EOF when reading a line

Until you uncomment the 2nd to last line.

Share:
14,276
Litwisha
Author by

Litwisha

Updated on August 21, 2022

Comments

  • Litwisha
    Litwisha almost 2 years

    I'm using python 2.7.6, and when calling raw_input(), there is an exception

    flight_name = raw_input('\nEnter the name of Flight: ')
    

    I found the solution, but why there appears such exception? Is it a bag?

    try:
          flight_name = raw_input('\nEnter the name of Flight: ')
    except (EOFError):
          break
    

    I'm using PyCharm.

  • Litwisha
    Litwisha over 10 years
    But I actually input some name of flight. Why it doesn't work?
  • tayfun
    tayfun over 10 years
    How do you input the name of the flight? Which keys are you using?
  • Litwisha
    Litwisha over 10 years
    For example London-Paris
  • Martijn Pieters
    Martijn Pieters over 7 years
    No you can't, not in the PyCharm IDE console. This only works if you are already in a terminal but stdin is a pipe.
  • Pylinux
    Pylinux over 7 years
    The question doesn't mention anything about PyCharm. If a user searches for raw_input + EOFError, as I did, he will find this question. Yes, buried in the comments there is a line mentioning PyCharm, but as long as the question doesn't say anything about PyCharm this is a valid answer.
  • Martijn Pieters
    Martijn Pieters over 7 years
    Without that comment the question is too vague to answer, and I'm pondering closing it; the alternative is that we edit that detail in. Even if this wasn't just about an IDE, setting sys.stdin to /dev/tty only works if there is a TTY to connect to, and if stdin isn't already connected to a TTY.