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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With