python - 如何使用 python http.server 运行 CGI "hello world"

标签 python http python-3.x cgi

我使用的是 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/

相关文章:

python - Python 整数是线程安全的吗?

python - pygame.transform.scale 在 "game"表面上不起作用

iphone - 在使用 ASIHTTPRequest 请求图像期间何时收到响应代码?

python - Pandas 中的日期时间转换问题

python - IIS 上的 Django : PyISAPIe or FastCGI or WSGI or Helicon Zoo or DjangoWindowsTools

c# - 将文本文件添加到我的代码的开头会导致解析错误

python - 确定 Pandas 的年度营业年度

python - Python bitshift 操作符如何转换为 Airflow 中的 set_downstream 和 set_upstream 功能

http - 在wireshark中数据包的TCP ACK

http - 使用 `http.NewRequest(...)` 发出 URL 编码的 POST 请求