【问题标题】:run python script as cgi apache server将 python 脚本作为 cgi apache 服务器运行
【发布时间】:2013-03-30 11:17:39
【问题描述】:

我正在尝试使用 Apache 服务器使 python 脚本作为 cgi 运行。我的脚本看起来像这样:

  #!/usr/bin/python
  import cgi
  if __name__ == "__main__":

  print("Content-type: text/html")
  print("<HTML>")
  print("<HEAD>")

我已经在httpd.conf中做了必要的配置(在我看来):

  <Directory "/opt/lampp/htdocs/xampp/python">
  Options +ExecCGI
  AddHandler cgi-script .cgi .py
  Order allow,deny
  Allow from all
  </Directory>

我已经用chmod设置了脚本的执行权限

但是,当我尝试通过 localhost 访问脚本时,出现错误 500:End of script output before headers:script.py 可能是什么问题呢?该脚本是在类似 Unix 的环境中创建的,所以我认为 clrf vs lf 的问题不成立。非常感谢。

【问题讨论】:

  • if 子句中的脚本中是否没有缩进,或者您只是这样粘贴?
  • python -m SimpleHTTPServer 是“一种”在 Python 中运行 HTTP 服务器的想法。

标签: python apache cgi


【解决方案1】:

我认为您在

之后缺少打印语句
print("Content-type: text/html")

CGI 脚本的输出应由两部分组成,以空行分隔。第一部分包含一些标头,告诉客户端什么类型的数据 关注。

第二部分通常是 HTML,它允许客户端软件显示带有标题、内嵌图像等的格式良好的文本。

可能看起来像

#!/usr/bin/env python

print "Content-Type: text/html"
print
print """
    <TITLE>CGI script ! Python</TITLE>
    <H1>This is my first CGI script</H1>
    Hello, world!
"""

更多详情请访问python-cgi

对于python3

#!/usr/bin/env python3

print("Content-Type: text/html")
print()
print ("""
    <TITLE>CGI script ! Python</TITLE>
    <H1>This is my first CGI script</H1>
    Hello, world!
"""
)

【讨论】:

  • 非常感谢,我尝试了\n\n 和 Python 2 语法(Xampp 和 Python 3),但没有成功。
猜你喜欢
  • 2015-03-11
  • 2012-07-27
  • 2016-12-08
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多