剛看接受Python,對於他的配置什麼的都不懂
今天寫了個Python文件想跟php一樣的執行以下,就看了下
Apache對CGI是支持的,想到Apache的時候,同時也想到了配置文件--httpd.conf
文件的目錄在:
/etc/apache2/httpd.conf
找個合適的工具打開修改,vim也好文本編輯也好
(我喜歡用Sublime,因爲顏色黑乎乎的 似乎高大上一樣)
1、搜索:mod_cgi.so會找到下面這句,沒有修改過的話,他是前面加#,被註釋掉的,我們去掉註釋
LoadModule cgi_module libexec/apache2/mod_cgi.so
2、搜索:AddHandler 會找打下面這句話,如果是註釋掉的話,同樣我們去掉註釋,後面的.pl .py .sh是自己追加的
AddHandler cgi-script .cgi .pl .py .sh
3、修改CGI的工作目錄(改到自己合適的位置)
我的內容跟網上說的一些有些不大一樣,通過ScriptAlias搜索
我的原來的是這樣的
#ScriptAliasMatch ^/cgi-bin/((?!(?i:webobjects)).*$) "/Library/WebServer/CGI-Executables/$1"<span style="font-family: Consolas, 'Courier New', Courier, mono, serif;"></span>
我就直接把他註釋掉了,然後改成了下面這樣
ScriptAlias /Documents/ /Library/WebServer/Documents/
因爲我的Apache的工作目錄就是在這個下面。
4、還有一個關於CGI的一個Directory
<Directory "/Library/WebServer/<span style="font-family: Consolas, 'Courier New', Courier, mono, serif;">CGI-Executables</span><span style="font-family: Consolas, 'Courier New', Courier, mono, serif;">"></span>
AllowOverride None
Options None
Require all granted
</Directory>
如果只是把上面的路徑改成Documents的路徑,執行還是不行
正確的是下面這個
<Directory "/Library/WebServer/Documents">
AllowOverride None
Options +ExecCGI
Order allow,deny
Allow from all
</Directory>
5、我們寫個簡單py文件放在Documents下面,名字存儲爲pyCGI.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
print "Content-type:text/html"
print # 空行,告訴服務器結束頭部
print '<html>'
print '<head>'
print '<meta charset="utf-8">'
print '<title>Hello Word - 我的第一個 CGI 程序!</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! 我是來自菜鳥教程的第一CGI程序</h2>'
print '</body>'
print '</html>'
6、重啓Apache
sudo /usr/sbin/apachectl restart
7、文件保存後修改 pyCGI.py,修改文件權限爲 755:
chmod 755 <span style="color: rgb(51, 51, 51); font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 14px; background-color: rgb(248, 248, 248);">pyCGI.py</span>
7、執行
http://localhost/pyCGI.py
這樣就執行成功了