Problem running Python script as cron job

Mitch Chapman chapman at
Mon Apr 10 16:11:52 EDT 2000

There are a couple of ways to force your output to be immediately 

An ugly solution is a sys.stdout.flush() after every print statement.

A less ugly solution is to reopen sys.stdout as soon as
your script starts up, and to turn off output buffering:
  sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

I thought it used to be possible to do a setbuf on the file object,
provided you hadn't already written to it.  But this appears not to
be the case.

Another option is to change your cron job so it sets the 
PYTHONUNBUFFERED environment variable before starting your program.
Something like this might work:

  /usr/bin/env PYTHONUNBUFFERED=1 /path/to/statsthing -r >/usr/local/tmp/.log

For that matter you could write a shell script wrapper which
set the environment variable, then invoke it from cron:

  /path/to/statsthing -r >/usr/local/tmp/.log

Here's hoping this is more help than hindrance...

Mitch Chapman
chapman at

"William R. Dickson" wrote:
> In article <0004071555090M.01234 at>, Patrick Phalen
> <python-list at> wrote:
> > [William R. Dickson, on Fri, 07 Apr 2000]
> > :: Anybody know of any issues with running python scripts from Cron?
> >
> > No. I've had multiple Python scripts running every one, two, five and
> > ten minutes around the clock for years on multiple servers without
> > problems. [...]
> I think so too, but I can't find it, because the script runs flawlessly
> every time I run it by hand, and the buffer never flushes the output to
> the log when it's run by Cron.

More information about the Python-list mailing list