运行 一个带有 python 的简单 cgi 网络服务器,但在浏览器上没有显示

Running a simple cgi webserver with python, but nothing shown on browser

我正在尝试 运行 使用以下 python 脚本 (hello.py) 的 cgi 网络服务器:

print ('Content-Type: text/html')
print
print ('<html>')
print ('<head><title>Hello from Python</title></head>')
print ('<body>')
print ('<h2>Hello from Python</h2>')
print ('</body></html>')

我把hello.py放在我运行宁python目录下的cgi-bin文件夹里。 在命令 window 上,我使用以下命令启动了 Web 服务器:

python -m http.server --bind localhost --cgi 8000

然后我打开了一个浏览器: http://localhost:8000/cgi-bin/hello.py

浏览器打开了,但是里面是一片空白,没有任何显示,而按照脚本应该显示"Hello from python"。 这些是后台显示的信息,好像没有错误。

C:\python_dir>python -m http.server --bind localhost --cgi 8000
Serving HTTP on 127.0.0.1 port 8000 (http://127.0.0.1:8000/) ...
127.0.0.1 - - [17/Feb/2018 15:14:41] "GET /cgi-bin/hello.py HTTP/1.1" 200 -
127.0.0.1 - - [17/Feb/2018 15:14:41] command: C:\python_dir\python.exe -u 
C:\Users\user\cgi-bin\hello.py ""
127.0.0.1 - - [17/Feb/2018 15:14:41] CGI script exited OK

这是我第一次启动网络服务器,我不知道哪里出了问题。

您的脚本 returns 一切都是 header 内容,而不是 body 您预期的那样,如快速 curl 调用所示:

curl --verbose localhost:8000/cgi-bin/hello.py

* HTTP 1.0, assume close after body
< HTTP/1.0 200 Script output follows
< Server: SimpleHTTP/0.6 Python/3.6.4
< Date: Sat, 17 Feb 2018 20:41:26 GMT
< Content-Type: text/html
< <html>
< <head><title>Hello from Python</title></head>
< <body>
< <h2>Hello from Python</h2>
< </body></html>
* Closing connection 0

通过分离 headers 和内容,服务器能够区分 headers 和 body:

print ('Content-Type: text/html')
print ('\n')
print
...

给出:

* HTTP 1.0, assume close after body
< HTTP/1.0 200 Script output follows
< Server: SimpleHTTP/0.6 Python/3.6.4
< Date: Sat, 17 Feb 2018 20:45:35 GMT
< Content-Type: text/html
<

<html>
<head><title>Hello from Python</title></head>
<body>
<h2>Hello from Python</h2>
</body></html>
* Closing connection 0