如何在Python2和Python3中运行和使用简单的HTTP服务器?

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
SimpleHTTPServer In Python2 From Commandline
SimpleHTTPServer In Python2 From Commandline
Python2中的SimpleHTTPServer从命令行

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
SimpleHTTPServer In Python2 As Code
SimpleHTTPServer In Python2 As Code
Python2中的SimpleHTTPServer作为代码

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
SimpleHTTPServer In Python3 From Commandline
SimpleHTTPServer In Python3 From Commandline
Python3中的SimpleHTTPServer从命令行

We can see from output that all network interfaces are listening port 8000 with HTTP protocol.

从输出中我们可以看到,所有网络接口都在侦听HTTP协议的端口8000。

LEARN MORE  Visual Studio Express Installation
了解更多Visual Studio Express安装

翻译自: https://www.poftut.com/how-to-run-and-use-simple-http-server-in-python2-and-python3/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值