Home > Software design >  is there anyway to handle EOFError with sys.stdio.readline() instead of input() in python
is there anyway to handle EOFError with sys.stdio.readline() instead of input() in python

Time:02-06

while True:
    try:
        n = int(input())
        print(n)
    except EOFError:
        break

I change the code above bit, to make it faster. like down below

import sys
while True:
    try:
        n = int(sys.stdin.readline())
        print(n)
    except EOFError:
        break

but I realized that sys.stdin.readline() doesn't make EOFError after I ran it. than input() is the only way to run the loop that I wrote? or is there any way faster than input

CodePudding user response:

input returns an empty line as '', and signals the end of the input with an EOFError.

readline returns an empty line as '\n' and signals the end of the input with ''.

In other words, input raises an exception because it alway strips the trailing end-of-line character and needs some way to distinguish between an empty line and no line.

For your code, you need to check the return value of sys.stdin.readline before you attempt to parse it as an int.

import sys


while (line := sys.stdin.readline()):
    n = int(line)

If readline returns an empty string, the loop exits.

CodePudding user response:

sys.stdin is a file object, so you could simply loop over it:

for line in sys.stdin:
    n = int(line)
    print(n)
  •  Tags:  
  • Related