python 3相当于”python-m simplehttpserver”是什么?

What is the Python 3 equivalent of “python -m SimpleHTTPServer”

python 3与python -m SimpleHTTPServer的等价物是什么?


来自文档:

The SimpleHTTPServer module has been merged into http.server in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.

所以,你的命令是python3 -m http.server


等效值为:

1
python3 -m http.server


使用2to3实用程序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ 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


除了Petr的答案之外,如果您希望绑定到特定的接口,而不是所有可以使用-b/--bind标志的接口。

1
python -m http.server 8000 --bind 127.0.0.1

上面的代码片段应该可以做到这一点。8000是端口号。80用作HTTP通信的标准端口。


在我的一个项目中,我对python 2和3运行测试。为此,我编写了一个单独启动本地服务器的小脚本:

1
2
$ 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 ...

作为别名:

1
2
3
$ 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。


命令python -m SimpleHTTPServer用于Linux。对Windows使用命令python -m http.server 7777