Python标准流重定向时adder.py报ValueError,需如何修改?
Let's break down what's going wrong here:
When you pipe writer.py's output to adder.py, once writer.py finishes printing all its lines, the pipe sends an EOF (end-of-file) signal. Your current adder.py code expects sys.stdin.readline() to throw an EOFError when this happens—but that's not how readline() works. Instead, it returns an empty string '' when it hits EOF.
You're slicing off the last character with [:-1], which turns that already-empty string into still-empty, then trying to convert it to an integer. That's exactly what's causing the ValueError: invalid literal for int() with base 10: '' message.
Here are a few simple fixes you can apply to adder.py:
Fix 1: Check for empty lines before converting
This is the most straightforward fix—just exit the loop when readline() returns an empty string:
import sys sum = 0 while True: line = sys.stdin.readline()[:-1] if not line: # Exit if we get an empty string (EOF) break sum += int(line) print(sum)
We remove the try/except block entirely here because readline() doesn't throw EOFError—it just gives us an empty string. Checking if not line catches that EOF case and stops the loop before we try to convert an empty string to an integer.
Fix 2: Keep the try/except but validate the line
If you want to keep the try/except structure (though it's not necessary here), you can add a check for empty lines in the else block:
import sys sum = 0 while True: try: line = sys.stdin.readline()[:-1] except EOFError: break else: if line: # Only process non-empty lines sum += int(line) print(sum)
This way, even if we get an empty string from readline(), we skip the conversion step entirely.
Fix 3: Use a for loop for cleaner code
Python lets you iterate directly over sys.stdin, which automatically handles EOF for you. This makes the code shorter and easier to read:
import sys sum = 0 for line in sys.stdin: cleaned_line = line.strip() # Remove newline characters and extra whitespace if cleaned_line: # Skip empty lines sum += int(cleaned_line) print(sum)
The strip() method takes care of any trailing newlines (so you don't need [:-1]) and also handles any accidental blank lines that might come through the pipe.
All three of these fixes will correctly calculate the sum of the numbers from writer.py without throwing an error.
内容的提问来源于stack exchange,提问作者Sarang Manjrekar

