• Python HTTP Server


    1. Python HTTP Server

    1.1. Python 内置

    Python 2:

    $ python -m SimpleHTTPServer 9000
    
    • 1

    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.

    $ python3 -m http.server
    Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
    
    • 1
    • 2

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

    $ python3 -m http.server 8080
    Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...
    
    • 1
    • 2

    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:

    $ python3 -m http.server 80
    Traceback (most recent call last):
      ...
    PermissionError: [Errno 13] Permission denied
    
    • 1
    • 2
    • 3
    • 4

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

    $ 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/) ...
    
    • 1
    • 2

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

    $ python -m http.server -b "::"
    Serving HTTP on :: port 8000 (http://[::]:8000/) ...
    
    • 1
    • 2

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

    $ python3 -m http.server -d ~/Pictures/
    Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
    
    • 1
    • 2

    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:

    $ cd /usr/lib/python3.8/
    $ python3 -m http.server
    Traceback (most recent call last):
      ...
    AssertionError: SRE module mismatch
    
    • 1
    • 2
    • 3
    • 4
    • 5

    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:

    $ 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/) ...
    
    • 1
    • 2
    • 3
  • 相关阅读:
    设计模式之迭代器模式
    Nginx编译安装+监控模块vts
    在 DjangoStarter 中集成 TailwindCSS
    javaweb 通过JDBC连接Mysql 数据库
    用户和组+切换用户命令
    虚拟运营商与实体运营商的apn匹配逻辑
    信息学奥赛初赛天天练-89-CSP-S2023基础题1-linux常用命令、完全平方数、稀疏图、队列、散列表、二叉树、哈夫曼树
    一文带你搞懂ArrayList 从源码角度剖析底层原理
    Docker快速部署Mysql
    Java如何解析html里面的内容并存到数据库
  • 原文地址:https://blog.csdn.net/wan212000/article/details/132909406