我使用的是 Windows 7 和 Python 3.4.3。我想在我的浏览器中运行这个简单的 helloworld.py 文件:
print('Content-Type: text/html')
print( '<html>')
print( '<head></head>')
print( '<body>')
print( '<h2>Hello World</h2>')
print( '</body></html>')
我做的是:
1) 转到命令行 C:\Python
(安装 python 的位置)
2) 运行:python -m http.server
3) 进入 Firefox 并输入 http://localhost:8000/hello.py
但是,浏览器只是打印 hello.py 文件的内容,而不是“Hello World”。
我该如何解决?
最佳答案
来自 the http.server
docs :
CGIHTTPRequestHandler
can be enabled in the command line by passing the--cgi
option:
$ python3 -m http.server --bind localhost --cgi 8000
将你的脚本放入cgi_directories
:
This defaults to
['/cgi-bin', '/htbin']
and describes directories to treat as containing CGI scripts.
在浏览器中打开:
$ python -mwebbrowser http://localhost:8000/cgi-bin/hello.py
哪里 hello.py
:
#!/usr/bin/env python3
print("Content-Type: text/html\n")
print("<!doctype html><title>Hello</title><h2>hello world</h2>")
我必须让它在 POSIX 上可执行:chmod +x cgi-bin/hello.py
。
关于python - 如何使用 python http.server 运行 CGI "hello world",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30516414/