8

a similar question has been asked before, but the answers suggested a workaround which is not applicable to my situation.

An email message is piped from mutt to a script, and is read from STDIN:

message = sys.stdin.read()
# message is parsed and URLs are printed as a list to choose from...
selected_index = raw_input('Which URL to open?')

I understand that raw_input() will get the EOF left by read(), but is there a way to 'reset' STDIN?

4
  • What system are you on? On Linux, this works fine! Commented Nov 7, 2011 at 9:23
  • Mac OS X (10.7). Alex Martelli suggested re-opening STDIN here, but that does not seem to work for me. Commented Nov 7, 2011 at 9:26
  • I just confirmed that the very same exception is thrown on a GNU/Linux system (CentOS). When I manually feed STDIN (terminating the input with CTRL-D), the script works fine, but calling ./script.py < message produces the problem described above. Commented Nov 7, 2011 at 10:48
  • OS X had similar problems in the past, but they were supposed to be fixed in Python 2.7 (I'm on 2.7.1). Commented Nov 7, 2011 at 16:47

2 Answers 2

6

Have you tried this:

message = sys.stdin.read()
sys.stdin = open('/dev/tty')
selected_index = raw_input('Which URL to open?')

This works on Linux; maybe it will work for OSX too.

Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately, it does not work (this is the solution proposed for the question I linked to in my first post). In the modified form, the script awaits input before arriving at the raw_input function, and the error occurs once I hit return.
This is odd – I must have done something wrong before: It works now. Thanks!
Nice hack! Linux FTW
0

Try to reset STDIN using sys.stdin.seek(0)

Reference: http://docs.python.org/library/fileinput.html

1 Comment

That helps a bit – the EOFError exception is gone, but the raw_input is now ignored entirely (i.e. the script proceeds without waiting for user input).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.