Misunderstanding buffering - flushing isn't

Skip Montanaro skip.montanaro at gmail.com
Wed Nov 5 17:44:46 CET 2014


I've been developing a little web server. The request handler
subclasses SimpleHTTPRequestHandler. It has a do_GET method which
figures out what work to actually do, then ends with this:

    def do_GET(self):
        ...
        sys.stdout.flush()
        sys.stderr.flush()

As it's still being actively developed, I've been dumping all sorts of
diagnostic prints to stdout and stderr. I've been running it directly
in a terminal window (this is an openSuSE system), but wanted to
capture stdout and stderr for post-mortem analysis, so I wrote this
little shell script:

    #!/bin/bash

    PORT=${1:-8008}
    BASE=$(dirname $0)

    echo port=$PORT pid=$$ > ${PORT}.stdout

    while true ; do
	python ${BASE}/httpserver.py $PORT >> ${PORT}.stdout 2> ${PORT}.stderr
	sleep 1
    done

I figured everything would be flushed to the respective .stdout and
.stderr files at the end of every request, but that appears not to be
the case. Do I have to run the python command with the -u flag to
guarantee each request's output is immediately available in the output
file at the end of each request?

Thx,

Skip



More information about the Python-list mailing list