How to tell whetehr Python script called as CGI or from command line?

Steve Holden steve at holdenweb.com
Mon Apr 16 08:30:08 EDT 2007


rowan at sylvester-bradley.org wrote:
> I'm writing a Python script that can either be called as a Cron job or
> as a web page (i.e. as a CGI in response to an HTTP request). This is
> to process the mailboxes on my web server (to which I don't have
> command line access) to remove old messages. How do I find out whether
> the script has been called as a Cron job or as a CGI? I need to know
> this so I can format the output correctly, e.g. if this is a web
> request I need to start the output with "Content-type: text/html\n
> \n<html>", to do newlines by "<p>" or "<br>" etc.
> 
> Can I just access some header line which will always have a value in a
> web request, but which will be None if running from the command line
> or as a Cron job, or something similar? How?
> 
> Thanks - Rowan
> 
The CGI standard requires that the calling server sets several 
environment variables, so you could test for the presence of one or more 
of those - this is only going to be indicative, though, since any shell 
could have the same variables set in its environment.

import os
if "QUERY_STRING" in os.environ:
     # CGI script

might work.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Recent Ramblings       http://holdenweb.blogspot.com




More information about the Python-list mailing list