最近在自学python3,学到CGI编程时愣住了,居然没有说windows环境下如何进行测试,此文章紧做此纪录
一:程序创建
在windows桌面创建www文件夹,同时在www文件夹下面创建cgi-bin文件夹,结构如下
二:CGI编程
在cgi-bin目录下创建hello.py,写入以下内容,代码中含中文乱码解决办法
#!/usr/bin/python
import codecs, sys
sys.stdout = codecs.getwriter('utf8')(sys.stdout.detach()) #不加乱码
print ("Content-type:text/html")
print () # 空行,告诉服务器结束头部
print ('<html>')
print ('<head>')
# windows乱码也可以直接删除这一句 和上面的 codecs.getwriter('utf-8),如果编码确认为UTF-8情况下
print ('<meta charset="UTF-8" />')
print ('<title>CGI TEST 测试</title>')
print ('</head>')
print ('<body>')
print ('<h2>CGI TEST 测试</h2>')
print ('</body>')
print ('</html>')
三: 运行
cmd进入www目录,注意是www目录,不是cgi-bin目录
输入命令:( 这里8080代表启动端口,可自定义)
python -m http.server --cgi 8080
四:访问
http://localhost:8080/cgi-bin/hello.py