Python 3 相当于python -m SimpleHTTPServer
什么?
7 回答
从文档:
该
SimpleHTTPServer
模块已合并到http.server
Python 3.0 中。将源转换为 3.0 时,2to3 工具将自动调整导入。
因此,您的命令是python -m http.server
,或者根据您的安装,它可以是:
python3 -m http.server
等效的是:
python3 -m http.server
使用 2to3 实用程序。
$ cat try.py
import SimpleHTTPServer
$ 2to3 try.py
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored try.py
--- try.py (original)
+++ try.py (refactored)
@@ -1 +1 @@
-import SimpleHTTPServer
+import http.server
RefactoringTool: Files that need to be modified:
RefactoringTool: try.py
2to3
像许多 * nix utils 一样,stdin
如果传递的参数是-
. 因此,您可以在不创建任何文件的情况下进行测试,如下所示:
$ 2to3 - <<< "import SimpleHTTPServer"
除了 Petr 的回答之外,如果您想绑定到特定接口而不是您可以使用-b
或--bind
标记的所有接口。
python -m http.server 8000 --bind 127.0.0.1
上面的代码片段应该可以解决问题。8000 是端口号。80 用作 HTTP 通信的标准端口。
正如大家所提到的, http.server模块相当于python -m SimpleHTTPServer
.
但作为来自https://docs.python.org/3/library/http.server.html#module-http.server的警告
警告:
http.server
不建议用于生产。它只实现基本的安全检查。
用法
http.server 也可以使用-m
解释器的开关直接调用。
python -m http.server
上述命令将默认在端口号上运行服务器8000
。您还可以在运行服务器时明确给出端口号
python -m http.server 9000
上面的命令将在端口 9000 而不是 8000 上运行 HTTP 服务器。
默认情况下,服务器将自己绑定到所有接口。选项 -b/--bind 指定它应该绑定的特定地址。支持 IPv4 和 IPv6 地址。例如,以下命令使服务器仅绑定到 localhost:
python -m http.server 8000 --bind 127.0.0.1
或者
python -m http.server 8000 -b 127.0.0.1
Python 3.8 版本还支持绑定参数中的 IPv6。
目录绑定
默认情况下,服务器使用当前目录。该选项-d/--directory
指定它应该向其提供文件的目录。例如,以下命令使用特定目录:
python -m http.server --directory /tmp/
在 python 3.7 中引入了目录绑定
在我的一个项目中,我针对 Python 2 和 3 运行测试。为此,我编写了一个小脚本,它独立启动本地服务器:
$ python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')
Serving HTTP on 0.0.0.0 port 8000 ...
作为别名:
$ alias serve="python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')"
$ serve
Serving HTTP on 0.0.0.0 port 8000 ...
请注意,我通过conda 环境控制我的 Python 版本,因为我可以使用python
而不是python3
使用 Python 3。
只是想添加对我
有用的内容python3 -m http.server 8000
:(您可以在此处使用任何端口号,但当前正在使用的端口号除外)