Python EOF Error in raw_input()

强颜欢笑 提交于 2019-11-28 11:49:36

Yes, the problem is that your raw_input() is reading from standard input, which is the output of cat, which is at EOF.

My suggestion would be to eliminate the cat. It is not necessary; Python is perfectly capable of reading files on its own. Pass the file name on the command line, open it, and read it yourself.

import sys

for line in open(sys.argv[1]):
    # process line

If you need to handle multiple files, check out the fileinput module; it easily handles reading multiple files as if they were one, which is what cat does for you.

This works under windows (I tested it by running python cons.py < cons.py and was able to see the prompt and not get an error about EOF):

import sys

for line in sys.stdin:
    print line

sys.stdin = open('CON', 'r')
q = raw_input('---->')

Under Unix, you'd probably just have to replace 'CON' with something in the /dev dir.

The objective is to have the script print a warning to standard error and let me choose whether to ignore the warning and continue or quit entirely.

You want the choice to come from an interactive prompt, while the data comes from the file? Well, now you're doing something different from the original program: you're reading those two things from different places, where they came from the same place before. So you need to update your design to allow for that.

Why does the raw_input not wait for input

raw_input waits for as long as is necessary to get a line of input. If the standard input is being redirected from a file, then lines of input are always available immediately (well, limited by e.g. the hard disk speed), up until the EOF, at which point no more will ever be available. In short, it doesn't wait for you to answer the question for the same reason that it doesn't wait for you to supply the invoice data: because you aren't the data source any more once you redirect from the file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!