Python - how can I read stdin from the shell and send stdout to the shell and file

I want a Python script to read stdin from the shell (bash) and send stdout to the shell, as well as the 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 entering my input, which means that I cannot see the prompt when 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
+3
source share
2 answers
#!/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
+2
source

Look at this error, it looks like raw_input is writing its prompt to stderr.

http://bugs.python.org/issue1927

+1
source

All Articles