Python Batteries

  • Web Server

    % python3 -m http.server --help
    usage: server.py [-h] [--cgi] [-b ADDRESS] [-d DIRECTORY] [-p VERSION] [port]
    
    positional arguments:
    port                  bind to this port (default: 8000)
    
    options:
    -h, --help            show this help message and exit
    --cgi                 run as CGI server
    -b ADDRESS, --bind ADDRESS
                            bind to this address (default: all interfaces)
    -d DIRECTORY, --directory DIRECTORY
                            serve this directory (default: current directory)
    -p VERSION, --protocol VERSION
                            conform to this HTTP version (default: HTTP/1.0)
    
  • Format String to JSON, Since Python 3.9, the params --no-ensure-ascii was introduced

    # python -m json.tool --no-ensure-ascii
    echo '{"bridge":{"IPAMConfig":null,"Links":null,"Aliases":null,"NetworkID":"713f5badd1daa56533f9739286364b7f42ab0e56073cd9d1e143a901ba465248","EndpointID":"a2d0d989c4983178c7baae84fb634760f4a99cd3c17c09928c9b74a5ce9c0438","Gateway":"10.200.0.1","IPAddress":"10.200.0.2","IPPrefixLen":24,"IPv6Gateway":"","GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"MacAddress":"02:42:0a:c8:00:02","DriverOpts":null}}' | python -m json.tool
    {
        "bridge": {
            "IPAMConfig": null,
            "Links": null,
            "Aliases": null,
            "NetworkID": "713f5badd1daa56533f9739286364b7f42ab0e56073cd9d1e143a901ba465248",
            "EndpointID": "a2d0d989c4983178c7baae84fb634760f4a99cd3c17c09928c9b74a5ce9c0438",
            "Gateway": "10.200.0.1",
            "IPAddress": "10.200.0.2",
            "IPPrefixLen": 24,
            "IPv6Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "MacAddress": "02:42:0a:c8:00:02",
            "DriverOpts": null
        }
    }
    
  • Check whether the third modules are installed successfully

    % python -c "import paramiko"
    Traceback (most recent call last):
    File "<string>", line 1, in <module>
    ImportError: No module named paramiko
    % python3 -c "import IPy"
    %
    
  • Url decode UTF-8 in Python

    from urllib.parse import unquote
    url = unquote(url)
    

    示例:

    % python3
    Python 3.12.2 (main, Feb 20 2024, 04:30:04) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    >>> from urllib.parse import unquote
    >>> url = "https://zh.wikipedia.org/wiki/%E5%A6%82%E4%BD%95%E9%96%B1%E8%AE%80%E4%B8%80%E6%9C%AC%E6%9B%B8"
    >>> unquote(url)
    'https://zh.wikipedia.org/wiki/如何閱讀一本書'