3

I'd like to have a Python script read stdin from the shell (bash), and send stdout to shell as well a redirected file. I tried the following:

$ cat test.py
#!/usr/bin/python

val = raw_input("enter val: ")
print val

$ ./test.py | tee out
testing
enter val: testing

$ cat out
enter val: testing

For some reason, the raw_input prompt is printed after I type my input, which means I can't see the prompt as I type. With a bash script, I can get something similar to work.

$ cat test.sh
#!/bin/bash

echo "enter val: "
read val
echo $val

$ ./test.sh | tee out
enter val: testing
testing

$ cat out
enter val: testing
Ravi
  • 3,718
  • 7
  • 39
  • 57

2 Answers2

2
#!/usr/bin/python
import sys

print "enter val: ",
sys.stdout.flush()
val = raw_input()
print val

Or

#!/usr/bin/python
import sys

sys.stdout = sys.stderr
val = raw_input("enter val: ")
sys.stdout = sys.__stdout__
print val
tMC
  • 18,105
  • 14
  • 62
  • 98
1

See this bug, looks like raw_input writes its prompt to stderr.

http://bugs.python.org/issue1927

dda
  • 6,030
  • 2
  • 25
  • 34
rlawson
  • 160
  • 6
  • I don't think this is the problem. I tried the same thing as the OP, but used `print` to output the prompt, and the result was the same. – senderle Jun 02 '11 at 18:54
  • well it does it's just without the flush you see the same symptom - see tMCs answer – rlawson Jun 02 '11 at 19:00