假设我有一个基本的Python脚本,test.py:
#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>Hello world!</html>"
Run Code Online (Sandbox Code Playgroud)
如何确定脚本是否在本地执行,例如:
python test.py
Run Code Online (Sandbox Code Playgroud)
或通过网络浏览器调用,例如访问:
http://example.com/test.py
Run Code Online (Sandbox Code Playgroud)
这似乎没有在cgi模块的文档中解决.我认为结果可能有所不同,cgi.FieldStorage()但似乎没有.
我能想到的唯一方法是:
#!/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"
Run Code Online (Sandbox Code Playgroud)
这是最好和/或最理想的方法吗?为什么/为什么不呢?