Determine if Python script is being executed locally or as CGI
Question: Let's say I have a basic Python script, `test.py`:

    
    
    #!/usr/bin/python
    
    print "Content-type: text/html\n\n"
    print "<html>Hello world!</html>"
    

How would one determine if the script is being executed locally, e.g.:

    
    
    python test.py
    

Or being called via a web browser, e.g. visiting:

    
    
    http://example.com/test.py
    

This doesn't seem to be addressed in [the documentation for the `cgi`
module](http://docs.python.org/library/cgi.html). I thought there might be a
difference in the result of `cgi.FieldStorage()` but there doesn't seem to be
one.

The only way I can think to do it is as follows:

    
    
    #!/usr/bin/python
    import os
    
    print "Content-type: text/html\n\n"
    print "<html>Hello world!</html>"
    
    if 'REQUEST_METHOD' in os.environ :
        print "This is a webpage"
    else :
        print "This is not a webpage"
    

Is this the best and/or most ideal method? Why/why not?


Answer: That looks like the best method. There isn't much difference between being
called from the command-line and being started by the web server following a
HTTP request, except for the CGI environment variables, like REQUEST_METHOD.

