Nerd Paradise

Don't worry, I'm not selling anything. Just giving a shoutout to one of my open-source side projects:

I created a programming language for beginners and am looking for people to test it out. If you have a spare moment (particularly if you haven't programmed before) and you're interested in making 2D games, please check it out.

Home > Programming > EOF exceptions with raw_input and stdin in Python

EOF exceptions with raw_input and stdin in Python

If you've tried to take in input by piping a file into a python script and reading it via raw_input, you've probably run across the terrible EOF exception that arises at the end:

C:\Users\Blake\Desktop> < nums.txt
Traceback (most recent call last):
  File "C:\Users\Blake\Desktop\", line 10, in <module>
    line = raw_input()
EOFError: EOF when reading a line


After scouring the internet to find the "correct" fix for this thinking "gee, once I find this it'll make a great blog post" I am sorry to report that, alas, I could not find one. So I give you the best "half-assed" fix:

while True:
    value = raw_input()
    do_stuff(value) # next line was found
  except (EOFError):
    break #end of file reached

Sadly this seems to be the proper usage of raw_input when dealing with the end of the stream of input from piped input. I guess the strongly-typed, unit-testing, check-for-every-null software developer in me cringes at the idea of using exceptions under normal usage circumstances. In pretty much every other development platform, using exceptions are reserved for when things Really Go Wrong.

Oh well, Python can't be perfect in every way.

You are visitor #007811
Get notified about new posts by following the newfangled twitter account.
Best viewed with
© 1999 Nerd Paradise