gpt4 book ai didi

python - 确定 Python 脚本是在本地执行还是作为 CGI 执行

转载 作者:太空狗 更新时间:2023-10-29 21:47:46 26 4
gpt4 key购买 nike

假设我有一个基本的 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"

这是最好和/或最理想的方法吗?为什么/为什么不?

最佳答案

这看起来是最好的方法。除了 CGI 环境变量(如 REQUEST_METHOD)之外,从命令行调用和由 Web 服务器根据 HTTP 请求启动之间没有太大区别。

关于python - 确定 Python 脚本是在本地执行还是作为 CGI 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5077980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com