Python HTTP Server

目录

  • [1. Python HTTP Server](#1. Python HTTP Server)
    • [1.1. Python 内置](#1.1. Python 内置)

1. Python HTTP Server

1.1. Python 内置

Python 2:

sh 复制代码
$ python -m SimpleHTTPServer 9000

If you are running Python 3, you will get error as No module named SimpleHTTPServer. It's because in python 3, SimpleHTTPServer has been merged into http.server module. You can use below command to run python http server in Python 3.

sh 复制代码
$ python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

To explicitly set the port number that your HTTP server should be listening on, append it as a parameter:

sh 复制代码
$ python3 -m http.server 8080
Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...

Port 80 is a standard port reserved for HTTP traffic. However, if you'd like to start a local web server on that special port, then you'll have to run the corresponding command as the superuser with administrative privileges. Otherwise, you'll get another error:

sh 复制代码
$ python3 -m http.server 80
Traceback (most recent call last):
  ...
PermissionError: [Errno 13] Permission denied

You can bind a specific network interface or IP address by using the -b option:

sh 复制代码
$ python3 -m http.server -b 127.0.0.42 8080
Serving HTTP on 127.0.0.42 port 8080 (http://127.0.0.42:8080/) ...

To enforce a different address, you can use the -b option:

sh 复制代码
$ python -m http.server -b "::"
Serving HTTP on :: port 8000 (http://[::]:8000/) ...

You may instruct the server to associate its home address (/) with a completely different directory by specifying the optional -d parameter:

sh 复制代码
$ python3 -m http.server -d ~/Pictures/
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

The -d option may be your only choice in some cases. For instance, if you try to start the HTTP server in a directory where you installed your Python interpreter, then you may face the following problem:

sh 复制代码
$ cd /usr/lib/python3.8/
$ python3 -m http.server
Traceback (most recent call last):
  ...
AssertionError: SRE module mismatch

You can work around this issue by changing your working directory so that Python will no longer find this module in the file system. Then, start the server using the -d option to point it back to the desired directory:

sh 复制代码
$ cd ..
$ python3 -m http.server -d /usr/lib/python3.8/
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
相关推荐
草明2 分钟前
Mongodb 慢查询日志分析 - 1
数据库·python·mongodb
yyytucj4 分钟前
python--列表list切分(超详细)
linux·开发语言·python
大数据魔法师19 分钟前
1905电影网中国地区电影数据分析(一) - 数据采集、清洗与存储
爬虫·python
肖田变强不变秃33 分钟前
C++实现有限元计算 矩阵装配Assembly类
开发语言·c++·矩阵·有限元·ansys
王磊鑫37 分钟前
Java入门笔记(1)
java·开发语言·笔记
喜欢猪猪1 小时前
分布式与微服务:构建现代应用的关键架构
开发语言·php
硬件人某某某1 小时前
Java基于SSM框架的社区团购系统小程序设计与实现(附源码,文档,部署)
java·开发语言·社区团购小程序·团购小程序·java社区团购小程序
kucupung1 小时前
【C++基础】多线程并发场景下的同步方法
开发语言·c++
Quantum&Coder1 小时前
Objective-C语言的计算机基础
开发语言·后端·golang
五味香1 小时前
Java学习,List 元素替换
android·java·开发语言·python·学习·golang·kotlin