EOFError:读取一行时的EOF [英] EOFError: EOF when reading a line

查看:102
本文介绍了EOFError:读取一行时的EOF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定义一个函数来制作矩形的周长.代码如下:

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.

推荐答案

width, height = map(int, input().split())
def rectanglePerimeter(width, height):
   return ((width + height)*2)
print(rectanglePerimeter(width, height))

像这样运行它会产生:

% echo "1 2" | test.py
6

<小时>

我怀疑 IDLE 只是将单个字符串传递给您的脚本.第一个 input() 正在处理整个字符串.注意如果在调用 input() 之后放入一些打印语句会发生什么:


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():

width = input()
print(width)
height = input()
print(height)

运行 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

注意第一个打印语句打印了整个字符串'1 2'.第二次调用 input() 会引发 EOFError(文件结束错误).

Notice the first print statement prints the entire string '1 2'. The second call to input() raises the EOFError (end-of-file error).

所以一个简单的管道,比如我使用的那个,只允许你传递一个字符串.因此你只能调用 input() 一次.然后,您必须处理此字符串,将其拆分为空格,然后自己将字符串片段转换为整数.就是这样

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

width, height = map(int, input().split())

确实如此.

请注意,还有其他方法可以将输入传递给您的程序.如果您在终端中运行了 test.py,那么您可以分别输入 12 没有问题.或者,您可以使用 pexpect 编写程序来模拟终端,传递 12 以编程方式.或者,您可以使用 argparse 在命令行上传递参数,允许您调用你的程序

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 pexpect to simulate a terminal, passing 1 and 2 programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with

test.py 1 2

这篇关于EOFError:读取一行时的EOF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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