raw_input(), STRANGE behaviour

Dox33 Rens.Duijsens at gmail.com
Sat Jan 26 07:23:36 EST 2008


I ran into a very strange behaviour of raw_input().
I hope somebody can tell me how to fix this.
(Or is this a problem in the python source?)

I will explain the problem by using 3 examples. (Sorry, long email)
The first two examples are behaving normal, the thirth is
strange.......

I wrote the following flabbergasting code:
#-------------------------------------------------------------
print "1: This is the print statement."

# Now halt the program until someone hits enter
raw_input("2: This is the raw_input prompt.")

import sys
print "3: This is a possible solution. ",
sys.stdout.flush()
command = sys.stdin.readline()
#-------------------------------------------------------------
and saved it in the file 'script.py'.

*** First, normal behaviour to stdout
Now, I open a command line and run the following command:
python script.py

On screen appears, after a few 'enter' keys:
1: This is the print statement.
2: This is the raw_input prompt.
3: This is a possible solution.
All works fine......

*** Second, redirected stdout to file, normal behaviour.
>From the command prompt I run:
python script.py > stdout_catch.txt
The screen stays empty, and after a few 'enter' keys the prompt
reapears.

In the file 'stdout_catch.txt' are the lines:
1: This is the print statement.
2: This is the raw_input prompt.
3: This is a possible solution.
And again, all works fine......

*** Thirst, redirect stderr to file, STRANGE behaviour......
>From the command prompt I run:
python script.py 2> stderr_catch.txt
This should redirect strerr to the file and stdout should stay on the
screen.

But..... What happens?
After a few 'enter' keys, on screen apears:
1: This is the print statement.
3: This is a possible solution.

WHERE IS THE SECOND LINE?
It is in the file stderr_catch.txt!!!

**** See the problem?
Please Tell me? Why is the prompt produced by raw_input() printed to
the error channel? It should be stdout, just as the print statement
does.

Looking at the python source code on
http://svn.python.org/view/python/tags/r251/Python/bltinmodule.c?rev=54864&view=auto
[found: 'builtin_raw_input(PyObject *self, PyObject *args)'].

One thing that I notice is that the code checks whether stdin and
stdout are connected to a terminal ("isatty" function), but I do not
know why the prompt ends up on stderr then.....

**** What is the solution?
I have noticed this behaviour under DOS in Windows XP, Windows 2000,
Windows 2003 Server, Windows vista, and Linux. How do I get
raw_input() to send it's prompt to stdout?

Friendly greetings

Rens



More information about the Python-list mailing list