pythonstdineoferror

ValueError: invalid literal for int() : while using python stream redirection


I am using standard stream redirection in Python. I have a writer.py file as below.

for data in (123, 0, 999, 42):
    print('%03d' % data)

The output of it is being used as input to an addition program.

import sys 
sum = 0 
while True:
    try:
      line = sys.stdin.readline()[:-1]
    except EOFError: break
    else:
        sum += int(line)
print(sum)

Giving the first script's output to other as :

python writer.py | python adder.py

This gives me the error as :

 File "adder.py", line 9, in <module>
    sum += int(line)
ValueError: invalid literal for int() with base 10: ''

What needs to be changed in adder.py script.


Solution

  • Your adder.py file should look like this:

    import sys
    sum = 0
    while True:
        line = sys.stdin.readline()[:-1]
        if line:
            sum += int(line)
        else:
            break
    
    print(sum)
    

    I hope It will solve your problem.