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

查看:29
本文介绍了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]+"
")
          sys.stderr.write("continue Y or 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<的输出/code>,在 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天全站免登陆