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/) ...
相关推荐
KANGBboy10 小时前
Python eval安全隐患
开发语言·python
IT爱学堂10 小时前
java版数据结构和算法+AI算法和技能学习指南
java·开发语言
evans在进步11 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
淼澄研学11 小时前
Python结合大模型挖掘搜题长尾关键词实操指南
开发语言·python
FfHUCisI11 小时前
Golang - 信号量模式(Semaphore Pattern)
开发语言·后端·golang
m0_5474866612 小时前
《Java程序设计与实践 》全套PPT课件2026
java·开发语言
中科高级技工学校12 小时前
乌鲁木齐美术艺考技校实践分享
人工智能·python
灵析表格13 小时前
灵析表格财务函数深度实用性分析与实操教程
开发语言·ai·json·excel·wps
运维全栈笔记13 小时前
致远 OA HTTPS 配置避坑指南
网络协议·http·https
CodeBlog-star13 小时前
LLM能力与边界:多模态、幻觉、上下文窗口及开源模型对比
人工智能·python·开源·llm