.py文件在浏览器中显示代码而不是运行

时间:2012-04-12 13:08:48

标签: python cgi localhost

我正在尝试使用Python,但无法为localhost正确设置我的服务器(使用Ampps)。 Python通过IDLE和命令行运行得很好,但是,当我在浏览器中打开文件时,代码会显示而不会运行。

我按照这个http://www.imladris.com/Scripts/PythonForWindows.html教程设置了cgi,但它没有用。

这是我的“hello world”程序的代码,如果这有任何区别的话。

#!/usr/bin/env python
# -*#!/usr/bin/python

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'

有什么建议吗?

2 个答案:

答案 0 :(得分:6)

您的Web服务器将您的python代码视为静态文件而不是可执行文件。这里的目标是你希望Apache执行python并将stdout发送回用户的浏览器。

我不熟悉Ampps,但获得此设置的基本Apache流程是这样的。

  1. 编辑httpd.conf的Options行以包含ExecCGI
  2. 通过添加以下行来将您的python文件注册为httpd.conf作为cgi处理程序:
    AddHandler .py
  3. 重启Apache
  4. 确保你的shebang行(#!/ usr / bin / env python位在顶部)实际指向你的python可执行文件的路径。对于生活在C:上的python2.6,这可能是:
    #!\Python26\python
  5. 如果您的脚本必须是可移植的,而不是修改shebang行,而是将行ScriptInterpreterSource registry添加到httpd.conf,并确保Windows默认打开带有Python.exe的* .py文件。这可以通过双击脚本来测试。如果它没有执行,请右键单击它,选择打开,然后选择其他,然后浏览到您的python.exe。确保选中“始终使用此程序打开此类文件”框。有关此here
  6. 的Microsoft知识库文章

    最后,mod_wsgi或FastCGI是让Apache执行python的首选方法,先前保留优先级较低的流量站点(每天数千个请求的数量)。我还建议调查web​​框架,例如web.py(非常轻量级)或django(重量较重,但如果你收集用户输入或与数据库连接,可以节省大量时间。)

答案 1 :(得分:1)

给定的解决方案适用于树莓派3 B +:

1)尝试编辑:sudo nano /etc/apache2/sites-enabled/000-default.conf

2)在文件中添加以下代码:

    <Directory /var/www/html>
            Options +ExecCGI
            AddHandler cgi-script .py
            # DirectoryIndex index.py
    </Directory>

3)重新启动apache2:sudo服务apache2重新启动

4)在您的代码中只需在上面添加几行:

#!/usr/bin/env python3
import cgitb
cgitb.enable()
print("Content-Type:text/html;charset=utf-8")
print()
print("Hello world")

5)您的代码应该可以工作;)