End of file when reading a line in python

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[]:

width = input[]
print[width]
height = input[]
print[height]

Running echo "1 2" | test.py produces

1 2
Traceback [most recent call last]:
  File "/home/unutbu/pybin/test.py", line 5, in 
    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].

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[]]

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



So as we can see in the pictures above, despite having produced the expected output, our test case fails due to a runtime error EOFError i.e., End of File Error. Let's understand what is EOF and how to tackle it.

What is EOFError

In Python, an EOFError is an exception that gets raised when functions such as input[] or raw_input[] in case of python2 return end-of-file [EOF] without reading any input.

When can we expect EOFError

We can expect EOF in few cases which have to deal with input[] / raw_input[] such as:

  • Interrupt code in execution using ctrl+d when an input statement is being executed as shown below

  • Another possible case to encounter EOF is, when we want to take some number of inputs from user i.e., we do not know the exact number of inputs; hence we run an infinite loop for accepting inputs as below, and get a Traceback Error at the very last iteration of our infinite loop because user does not give any input at that iteration

n=int[input[]]
if[n>=1 and n=1 and n Exception -> EOFError

 The best practice to avoid EOF in python while coding on any platform is to catch the exception, and we don't need to perform any action so, we just pass the exception using the keyword “pass” in the “except” block.

Chủ Đề