raw_input and several modules that are part of the standard library that
handle input and output with stdout and stdin (cmd.py) do NOT - I repeat -
do NOT flush stdout before waiting for input.
No, I don't want to flush buffer stdout everytime I write to it. That is
wasteful and inefficient. I want to flush the buffer when I am done writing
to it, or when I make a call to raw_input(). (This has been brought up
before a long time ago - why is it not fixed? Why does Guido want it to
behave like this?)
If it is running with a terminal, then the underlying code (in C or the
Kernel, I am not sure) will flush stdout before reading input. However, it
does not automatically flush stdout before reading stdin if stdout and
stdin are not terminals.
That means if I write a program that forks off another process that runs a
python script that uses stdin and stdout, (using something like Popen3),
then the conversation goes something like this:
parent: (Waiting patiently for some information from the child)
child: (wrote to stdout but didn't flush the buffer, so he doesn't send
anything yet)
child: (expects input from stdin - which will be coming from the parent)
parent: (Waiting patiently for some information from the child)
programmer: (Going insane and pulling his hair out, screaming at the
computer bloody murder) BLOODY MURDER! BLOODY MURDER!
If raw_input and other modules that ask for input would flush stdout before
they wait for input, the conversation would look like this:
parent: (Waiting patiently for some information from the child)
child: (wrote to stdout and flushed the buffer)What is your command?
child: (expects input from stdin - which will be coming from the parent)
parent: (Receives the message)(writes to stdin of the child and flushes the
buffer)HAHA! YOU ARE NOW UNDER MY CONTROL!
child: (receives the message through stdin)SYNTAX ERROR.
programmer: (Much more relaxed now...)Now that the program is working, I
can get some sleep! Whew! (has pleasant dream of Python hacking...)
Should I turn on -u for the child script? That is silly. Just write
raw_input properly, and make everyone happy. If you don't, I'll be *forced*
to hack on the cpython code, and then you'll *really* regret it! =)
I am running Linux 2.4.14 and Python 2.1.2. I tested this bug in Python 2.2
and it is still there.
I posted a bug about cmd not flushing the buffer to sourceforge. I will
post another bug about raw_input not flushing the buffer. I will write
another bug report about the unresponsiveness to bug reports as well, as
there are a lot of bugs that aren't even addressed at sourceforge.
PLEASE PLEASE PLEASE! Examine your code. If you do not use raw_input, then
flush your buffers! Otherwise, we will not be able to fork off your
script/module and use it as a child process without -u.
Thank you.
Jonathan Gardner