tags:

views:

200

answers:

2

Hi to all, 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 ??

+9  A: 

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.
RichieHindle
Thanks a lot for your answer !!! I have just tried and it works...
IceMan85
+5  A: 

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.

S.Lott
Hi, thanks for the advice ! I will do as u suggested ...P.S. I've started reading your book, I really lake it !!!Bye
IceMan85