开发者

Determine if Python script is being executed locally or as 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开发者_JAVA技巧 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜