raw_input()中的Python EOF错误 [英] Python EOF Error in raw_input()

查看:238
本文介绍了raw_input()中的Python EOF错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在命令提示符下从用户那里获取输入.该程序以"cat text.txt | ./thescript.py"

I am trying to get input from the user at the command prompt. The program reads in data from a text file in the manner of "cat text.txt | ./thescript.py"

在有问题的脚本处,所有数据已经​​被读取,处理并放入列表列表中.

At the point of the script in question, all data has already been read in, processed, and put into a list of lists.

现在,我正在遍历该列表以查找有问题的项目.该代码基本上看起来像这样:

Now I am iterating through that list of lists looking for questionable items. The code basically looks like this:

for invoice in parsedlist:
      if invoice[-1] == 3:
          sys.stderr.write("triple duplicate at " + invoice[2]+' : ' + invoice[3]+"\n")
          sys.stderr.write("continue Y or N \n")
          answer = raw_input("Type your answer here")
          if answer == 'N':
              sys.exit(1)
          else: 
              pass`

此代码将导致EOFError.据我了解,在这种情况下,stdin是从cat读取的,并且因为它已经到达EOF,这就是为什么raw_input在这里得到EOF的原因? (我认为)目标是让脚本为标准错误打印警告,然后让我选择是否忽略警告并继续还是完全退出.最后,所有输出将输出到标准输出,并且将不包含任何错误警告或响应.我已经看到了使用try/exception的示例,但在这种情况下我无法理解. (例如,为什么raw_input不等待输入?)

This code results in an EOFError. From what I already understand, stdin is the read from cat in this case and since it has already reached EOF that is why raw_input gets EOF here? (I think) 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. In the end all output goes to std out and will not include any of the error warnings or responses. I have seen examples that use a try/exception but I have not been able to make sense of it in this context. (Eg. Why does the raw_input not wait for input?)

我认为我可能只是以错误的方式攻击了这个问题,从而造成了一个更好地绕过然后跳过的问题.一如既往地感谢您的任何帮助.

I think I may just be attacking this problem in the wrong way and thus creating a problem that could be better walked around then jumped over. Any help is appreciated as always.

推荐答案

是的,问题在于您的raw_input()正在从标准输入(即cat的输出)读取,该输出位于EOF.

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

我的建议是消除cat.没有必要; Python非常有能力自行读取文件.在命令行中传递文件名,打开它,然后自己阅读.

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

如果需要处理多个文件,请签出fileinput模块;它可以轻松地像读取多个文件一样处理多个文件,这就是cat为您完成的工作.

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.

这篇关于raw_input()中的Python EOF错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆