Python, who is calling my python module
Question
I have one Python module that can be called by a CGI script (passing it information from a form) or from the command line (passing it options and arguments from the command line). Is there a way to establish if the module has been called from the CGI script or from the command line ??
Solution
This will do it:
import os
if os.environ.has_key('REQUEST_METHOD'):
# You're being run as a CGI script.
else:
# You're being run from the command line.
OTHER TIPS
This is a really bad design idea. Your script should be designed to work independently of how it's called. The calling programs should provide a uniform environment.
You'll be happiest if you design your scripts to work in exactly one consistent way. Build things like this.
myscript.py - the "real work" - defined in functions and classes.
myscript_cgi.py - a CGI interface that imports myscript and uses the classes and functions.
myscript_cli.py - the command-line interface that parses the command-line options, imports myscript, and uses the classes and functions.
A single script that does all three things (real work, cgi interface, cli interface) is usually a mistake.