running system command in cgi problem

Carsten Gaebler clpy at snakefarm.org
Fri Feb 22 17:06:21 CET 2002


Felix Seeger wrote:

> I've writen a small cgi/python script that starts a command on the server.
> This command may take about 30 minutes to finish. So my browser becomes a
> timeout.
> 
> Is there any way to run the command, and while it works send the browser
> every 30 secs a please wait string + refresh.

You could fork a child process which executes the command and let the
parent process wait for it to finish and print keepalive messages in
the meantime. This could look like the following. Note the '-u'
argument to python; it ensures that output is not buffered but sent to
the browser immediately.


#! /usr/bin/python -u
import os, time

print "Content-Type: text/plain"
print

print "Forking child"
if os.fork() == 0:
    # child process
    time.sleep(20)  # your command here
    os._exit(0)
else:
    # controlling parent process
    while 1:
        # check if child has exited, but don't block
        (pid, status) = os.waitpid(-1, os.WNOHANG)
        if pid > 0:
            print "Child finished!"
            break
        else:
            print "Please wait!"
            time.sleep(4)


Hope this helps.
cg.
-- 
Save the earth - it's our only source of chocolate.



More information about the Python-list mailing list