Python 3 中 python -m SimpleHTTPServer 的等价命令是什么?
Python 2 的 python -m SimpleHTTPServer 在 Python 3 中改为 python -m http.server(模块重构更名)。默认 8000 端口,服务当前目录。
Python 3 的等价命令是 python -m http.server。Python 3 把 Python 2 的 SimpleHTTPServer 模块合并重构进了 http.server 包。
对比
# Python 2
python -m SimpleHTTPServer
# Python 3
python3 -m http.server
默认绑定所有接口并监听 8000 端口(本机预览建议显式 --bind 127.0.0.1),把当前目录作为静态站点目录,浏览器访问 http://localhost:8000。
常用参数
python3 -m http.server 8080 # 指定端口
python3 -m http.server -d /srv/files # 指定目录(3.7+)
python3 -m http.server -b 0.0.0.0 # 显式监听IPv4所有接口;省略bind也并非仅本机
类似的模块改名(Python 2 → 3)
| Python 2 | Python 3 |
|---|---|
| SimpleHTTPServer | http.server |
| BaseHTTPServer | http.server |
| urllib2 | urllib.request、urllib.error 等 |
| ConfigParser | configparser |
| Queue | queue |
安全提醒
http.server 只适合临时共享文件和本地调试:现代CLI使用线程服务器,且Python3.14+支持TLS选项,但仍缺生产所需的完整安全控制,默认没有认证,不要暴露到公网或用于生产。它可能跟随符号链接提供目录外文件,所选根目录也不是安全沙箱。
常见问题(FAQ)
Q:为什么命令行里要写 python3 而不是 python?
A:很多系统(尤其 macOS 和部分 Linux)中 python 仍指向 Python 2 或不存在,显式写 python3 最稳妥。
Q:启动后如何停止?
A:前台运行时 Ctrl+C。
Q:能显示访问日志吗?
A:http.server 会把每个请求打到终端(GET /path 200),这是默认行为,无需配置。