Python EOFError:读取一行时的EOF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17675925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
EOFError: EOF when reading a line
提问by Chimp
I am trying to define a function to make the perimeter of a rectangle. Here is the code:
我正在尝试定义一个函数来制作矩形的周长。这是代码:
width = input()
height = input()
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
I think I haven't left any arguments opened or anything like that.
我想我没有留下任何争论或类似的东西。
采纳答案by unutbu
width, height = map(int, input().split())
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
Running it like this produces:
像这样运行它会产生:
% echo "1 2" | test.py
6
I suspect IDLE is simply passing a single string to your script. The first input()
is slurping the entire string. Notice what happens if you put some print statements in after the calls to input()
:
我怀疑 IDLE 只是将单个字符串传递给您的脚本。第一个input()
是啜饮整个琴弦。请注意,如果您在调用 之后放入一些打印语句会发生什么input()
:
width = input()
print(width)
height = input()
print(height)
Running echo "1 2" | test.py
produces
运行echo "1 2" | test.py
产品
1 2
Traceback (most recent call last):
File "/home/unutbu/pybin/test.py", line 5, in <module>
height = input()
EOFError: EOF when reading a line
Notice the first print statement prints the entire string '1 2'
. The second call to input()
raises the EOFError
(end-of-file error).
注意第一个打印语句打印整个字符串'1 2'
。第二次调用input()
引发EOFError
(文件结束错误)。
So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input()
once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what
所以一个简单的管道,比如我使用的那个,只允许你传递一个字符串。因此你只能调用input()
一次。然后,您必须处理此字符串,将其拆分为空格,然后自己将字符串片段转换为整数。那是什么
width, height = map(int, input().split())
does.
做。
Note, there are other ways to pass input to your program. If you had run test.py
in a terminal, then you could have typed 1
and 2
separately with no problem. Or, you could have written a program with pexpectto simulate a terminal, passing 1
and 2
programmatically. Or, you could use argparseto pass arguments on the command line, allowing you to call your program with
请注意,还有其他方法可以将输入传递给您的程序。如果您test.py
在终端中运行,那么您可以毫无问题地分别输入1
和输入2
。或者,您可以使用pexpect编写一个程序来模拟终端,1
并以2
编程方式传递。或者,您可以使用argparse在命令行上传递参数,从而允许您使用
test.py 1 2
回答by astrognocci
convert your inputs to ints:
将您的输入转换为整数:
width = int(input())
height = int(input())
回答by Saurabh Raj
**The best is to use try except block to get rid of EOF **
**最好是使用try except块来摆脱EOF **
try: width = input() height = input() def rectanglePerimeter(width, height): return ((width + height)*2) print(rectanglePerimeter(width, height)) except EOFError as e: print(end="")