user3019917 user3019917 - 3 months ago 19
Python Question

python: read data from stdin and raw_input

I want to pass some data to a python script using echo and after that promote the user to input options. I am running through an

EOFError
which I think is happening since I read all data in
sys.stdin
. How do I fix this issue? Thanks!

code.py:

x = ''
for line in sys.stdin:
x += line
y = raw_input()


usage:

echo -e -n '1324' | ./code.py


error at
raw_input()
:

EOFError: EOF when reading a line

Answer

You just cannot send data through stdin (that's redirecting) and then get back the interactive mode.

When you perform a | b, b cannot read from standard input anymore. If it wants to do that, it will stop as soon as a finishes and breaks the pipe.

But when a finishes, it does not mean than you get hold of stdin again.

Maybe you could change the way you want to do things, example:

echo -n -e '1324' | ./code.py

becomes

./code.py '1234' '5678'

and use sys.argv[] to get the value of 1234, 5678...

import sys

x = ''
for line in sys.argv[1:]:
  x += line+"\n"

y = raw_input()

if you have a lot of lines to output, pass an argument which is a file and what you'll read

import sys

x = ''
for line in open(sys.argv[1],"r"):
  x += line

y = raw_input()
Comments