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 小时前
Kotlin函数由易到难
开发语言·python·kotlin
姑苏风2 小时前
《Kotlin实战》-附录
android·开发语言·kotlin
奋斗的小花生3 小时前
c++ 多态性
开发语言·c++
魔道不误砍柴功3 小时前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python
闲晨3 小时前
C++ 继承:代码传承的魔法棒,开启奇幻编程之旅
java·c语言·开发语言·c++·经验分享
_.Switch3 小时前
高级Python自动化运维:容器安全与网络策略的深度解析
运维·网络·python·安全·自动化·devops
老猿讲编程3 小时前
一个例子来说明Ada语言的实时性支持
开发语言·ada
Chrikk4 小时前
Go-性能调优实战案例
开发语言·后端·golang
幼儿园老大*4 小时前
Go的环境搭建以及GoLand安装教程
开发语言·经验分享·后端·golang·go
canyuemanyue4 小时前
go语言连续监控事件并回调处理
开发语言·后端·golang