9

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. 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?

Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82
  • Another idea: Do it like `/usr/bin/python myscript.py mysupersecret` every time you run the script locally, and then check if `sys.argv[1] == "mysupersecret"`, then this is called locally. When called from CGI `sys.argv` will not have the args (unless you have set them up, in which case you already know what to do). – Jay Dadhania Jul 11 '21 at 08:20

1 Answers1

8

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.

jd.
  • 10,678
  • 3
  • 46
  • 55