1

If I make a program "prog.py" in Python with this code:

#!/usr/bin/python3.3
# -*-coding:Utf-8 -*

while True:
    number = int(input())
    print(number * 2)

I have a file "numbers.txt" with that:

1
2
3
4
5
6
7
8
9
10

And I run it like that:

chmod +x prog.py
cat numbers.txt | ./prog.py

I get that:

2
4
6
8
10
12
14
16
18
20
Traceback (most recent call last):
  File "./prog.py", line 5, in <module>
    number = int(input())
EOFError: EOF when reading a line

Why this error?

Texom512
  • 4,785
  • 3
  • 16
  • 16
  • What's a extra enter? – Texom512 Jul 25 '15 at 16:34
  • Chek http://stackoverflow.com/questions/2953081/how-can-i-write-a-here-doc-to-a-file-in-bash-script ´files = [e.rstrip for e in (open(numbers.txt).readlines())]#a list´ Every print is new line. – dsgdfg Jul 25 '15 at 17:05

2 Answers2

1

This is because you are using

while True:

Replace it with

import sys
for line in sys.stdin:
    number = int(line.strip())
kampta
  • 4,748
  • 5
  • 31
  • 51
1

This is expected; you try to read from standard input with input without checking if you've reached the end of the file. However, it's better practice to iterate directly over the file sys.stdin than to repeatedly call input.

import sys

for line in sys.stdin:
    number = int(line)
    print(number * 2)

The iteration will stop automatically when you reach the end of the file, so there's no need to check for it explicitly.

chepner
  • 497,756
  • 71
  • 530
  • 681