Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if Python script is being executed locally or as CGI

Tags:

python

cgi

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?

like image 604
Dustin Ingram Avatar asked Feb 22 '11 12:02

Dustin Ingram


People also ask

How do I know if python script is running in the background?

Show activity on this post. Drop a pidfile somewhere (e.g. /tmp). Then you can check to see if the process is running by checking to see if the PID in the file exists. Don't forget to delete the file when you shut down cleanly, and check for it when you start up.

Does Python use CGI?

CGI stands for Common Gateway Interface in Python which is a set of standards that explains how information or data is exchanged between the web server and a routine script.


1 Answers

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.

like image 175
jd. Avatar answered Oct 24 '22 07:10

jd.