假设我有一个基本的Python脚本test.py
:
#!/usr/bin/python
print "Content-type: text/html\n\n"
print "<html>Hello world!</html>"
如何确定脚本是否在本地执行,例如:
python test.py
或通过网络浏览器调用,例如来访:
http://example.com/test.py
the documentation for the cgi
module似乎没有解决这个问题。我认为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"
这是最好和/或最理想的方法吗?为什么/为什么不呢?
答案 0 :(得分:6)
这看起来是最好的方法。除了CGI环境变量(如REQUEST_METHOD)之外,在HTTP命令之后从命令行调用和Web服务器启动之间没有太大区别。