0

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.

3
  • Most likely because you're trying to cast a line terminator to int. Commented Jan 23, 2018 at 11:26
  • @BoboDarph, yes i too guess so. But shud 'except EOFError: break' not be able to deal with this ? Commented Jan 23, 2018 at 11:39
  • EOF happens on the next read after that. Commented Jan 23, 2018 at 11:43

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

When you call readline() it returns the current line of the file (stdin is treated as a file too) or returns a newline character is EOF has reached. (doc)

Your writer.py returns just 4 elements, but your adder.py reads input in an infinite loop so when it has read that 4 numbers, the stdin is empty and readline() returns a newline character, and you cannot convert a blank character to int. In fact, you are using readline()[:-1] so in your case you are getting just an empty string.

On the other hand, your print is after the infinite loop, so it will never be called (even if you stop it with a KeybordInterrupt). I suggest to use something like:

line = sys.stdin.readline()[:-1]
while line:
    #do stuff
    line = sys.stdin.readline()[:-1]

2 Comments

When i use this, it is skipping the first element and giving the sum of rest three elements.
@Sarang You should put the rest of the code where the "do stuff" is. The second readline must be at the end of the loop. You can use a break instead, like rishi kant does in his solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.