0

My program first read something from stdin. After finished, ask the user to input something just like the codes shown in below:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

a = sys.stdin.readline()
print 'stdin is ' + a

b = raw_input("Input: ")
print 'user input: ' + b

When I run echo "111" | ./main.py It output:

stdin is 111

Input: Traceback (most recent call last):
  File "./main.py", line 9, in <module>
    b = raw_input("Input: ")
EOFError: EOF when reading a line

Any idea how it could work?

Env: Python 2.7.11 (default, Dec 5 2015, 14:44:53) with OSX

Thanks!

edit: In order to eliminate the confusion, the code now change to the following:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:

import sys

a = ''
for line in sys.stdin:
  a += line
print 'stdin is ' + a
b = raw_input("Input: ")

edit2: Try (echo -e "something" && cat) | ./main.py, but no luck

edit3: the best way I can think about is to pass a file descriptor instead of stdin:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:

import sys

a = ''
with open(sys.argv[1]) as f:
  for line in f:
    a += line
print 'stdin is ' + a
b = raw_input("Input: ")

Run as ./main1.py <(echo 'fasfasfasfa').

Please let me know if you have a better solution.

gany
  • 3
  • 4
  • I'm pretty sure if you pass a specific echo to a program, it is considered to have an EOF because that was the end of the file passed to it. – Eli Sadoff Jun 23 '16 at 02:58
  • Yes, I understand that. Do you know what I need to do with it so that I can get the user`s input during the program running time? – gany Jun 23 '16 at 03:50
  • See https://unix.stackexchange.com/questions/103885/piping-data-to-a-processs-stdin-without-causing-eof-afterward – zondo Jun 23 '16 at 03:53
  • Hi zondo, thanks for your reply. I have tried the method the above post mentioned, `(echo -e "cmd 1\ncmd 2" && cat) | ./main.py` but it does not work. – gany Jun 23 '16 at 03:59
  • Your edit to "eliminate confusion" is enough different that the suggested solution does indeed not work. Try it with your old code. – zondo Jun 23 '16 at 04:07
  • Sorry for the confusion, I mean the situation for the code in "eliminate confusion" part. – gany Jun 23 '16 at 04:10
  • In your new code, you are asking Python to give you each line in stdin. If you run that interactively, you will see that you can keep typing more lines forever. The way to end the program is to hit Ctrl-D, or EOF. When you run the bash code that is given, the same is required: Ctrl-D. – zondo Jun 23 '16 at 04:13
  • See the other dupe, it's perfect. A small screenshot to help you http://i.stack.imgur.com/Mt2H3.png – Bhargav Rao Jun 23 '16 at 14:58

0 Answers0