Python provides different HTTP and related modules in builtin and 3rd party modules. Python also provides some basic HTTP server modules native. In this tutorial we will learn how to run HTTP server in Python2 and Python3.
Python在内置模块和第三方模块中提供了不同的HTTP和相关模块。 Python还提供了一些本地的基本HTTP服务器模块。 在本教程中,我们将学习如何在Python2和Python3中运行HTTP服务器。
Python2中的SimpleHTTPServer从命令行 (SimpleHTTPServer In Python2 From Commandline)
We will use SimpleHTTPServer
module for Python2. We will just provide the module name the port number we want to run HTTP server from commandline. In this example we will run from 8000
.
我们将对Python2使用SimpleHTTPServer
模块。 我们将只为模块名称提供要从命令行运行HTTP服务器的端口号。 在此示例中,我们将从8000
运行。
$ python2 -m SimpleHTTPServer 8000

This screenshot means web server is listening from all network interfaces for TCP port 8000 for our HTTP web server.
此屏幕快照表示Web服务器正在从所有网络接口侦听我们的HTTP Web服务器的TCP端口8000。
Python2中的SimpleHTTPServer作为代码 (SimpleHTTPServer In Python2 As Code)
More complete way to run a HTTP server is running a web server script. We will use following code which is named webserver.py
.
运行HTTP服务器的更完整方法是运行Web服务器脚本。 我们将使用以下名为webserver.py
代码。
import SimpleHTTPServer
import SocketServer
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
AND run like below.
然后像下面一样运行。
$ python2 webserver.py

Python3中的SimpleHTTPServer从命令行(SimpleHTTPServer In Python3 From Commandline)
As Python version 3 the name of the HTTP server is changed to the http.server . So we need to run following command from command line.
作为Python版本3,HTTP服务器的名称更改为http.server。 因此,我们需要从命令行运行以下命令。
$ python3 -m http.server 8000

We can see from output that all network interfaces are listening port 8000 with HTTP protocol.
从输出中我们可以看到,所有网络接口都在侦听HTTP协议的端口8000。
翻译自: https://www.poftut.com/how-to-run-and-use-simple-http-server-in-python2-and-python3/