我正在尝试使用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>'
有什么建议吗?
答案 0 :(得分:6)
您的Web服务器将您的python代码视为静态文件而不是可执行文件。这里的目标是你希望Apache执行python并将stdout发送回用户的浏览器。
我不熟悉Ampps,但获得此设置的基本Apache流程是这样的。
AddHandler .py
#!\Python26\python
ScriptInterpreterSource registry
添加到httpd.conf,并确保Windows默认打开带有Python.exe的* .py文件。这可以通过双击脚本来测试。如果它没有执行,请右键单击它,选择打开,然后选择其他,然后浏览到您的python.exe。确保选中“始终使用此程序打开此类文件”框。有关此here。最后,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)您的代码应该可以工作;)