Python搭建简易静态HTTP服务器

为了给同事临时共享文件,我通过Python命令快速搭建了局域网HTTP服务器供其下载。关键命令是:python -m http.server

python -m命令简介

Python搭建简易静态HTTP服务器

python -m module-name
在 sys.path 中搜索指定名称的模块,并将其内容作为 main 模块来执行。

http.server模块

http.server模块定义了实现 HTTP 服务器( Web 服务器)的类。它会创建和侦听 HTTP 套接字,并将请求调度给处理程序。
http.server can also be invoked directly using the -m switch of the interpreter with a port number argument. this serves files relative to the current directory.(当前目录,即运行python命令时所在的目录)

启动服务器

示例:将我机器E盘下的student目录作为http服务器的路径
1、目录截图
Python搭建简易静态HTTP服务器
2、CMD启动命令
Python搭建简易静态HTTP服务器
3、浏览器查看
Python搭建简易静态HTTP服务器

备注

1、关于http.server的官方警告
Python搭建简易静态HTTP服务器
2、http.server模块绑定IP地址和指定路径的参数
-b/–bind 可以绑定IP地址,默认绑定本机所有IP地址。
–directory 可以指定路径,默认是python命令输入时的路径。(python 3.7之后才有的选项)