4

To receive input from stdin in python 2.7, I typically import sys and use sys.stdin. However, I have seen examples where raw_input is used to receive input from stdin, including multi-line input. How exactly can I use raw_input in place of sys.stdin? Here is an example problem:

input.txt:

Print
me
out

And I am running this command:

cat input.txt | python script.py

What can I put in script.py such that it will print out all lines of input using raw_input?

Rohan
  • 482
  • 6
  • 16

1 Answers1

0

You can do something like this:

while True:
    try:
        print raw_input()
    except EOFError:
        break

raw_input will only return single lines from stdin, and throws EOFError when EOF is read.

jacob
  • 4,656
  • 1
  • 23
  • 32
  • When will it throw an EOFError? – Rohan Jan 19 '16 at 04:11
  • https://latedev.wordpress.com/2012/12/04/all-about-eof/ – jacob Jan 19 '16 at 04:19
  • Why would this throw EOF? – Rohan Jan 19 '16 at 06:16
  • Also, each `raw_input` receives just one line of stdin? – Rohan Jan 19 '16 at 06:19
  • EOF is a way your operating system signifies that there is nothing more to be read from the reading source. `raw_input` is defined to keep returning lines from stdin until EOF is reached, and when it is reached it will throw a `EOFError`. – jacob Jan 19 '16 at 06:33
  • But after it reaches the end of stdin, won't `raw_input` then prompt for the user to enter new input? – Rohan Jan 19 '16 at 18:13
  • @Rohan: It would prompt the input source to enter more input, but you’re piping the input in from a file. If it’s reached the end of the file, there’s really no way for it to ‘ask the file for more input’, so it throws an `EOFError`. (Similarly, even if standard input were not redirected, the user can press control-D or equivalent to send an EOF to a program, which will again cause an `EOFError` to be thrown.) – icktoofay Jan 25 '16 at 04:15