Python标准库中隐藏的利器
Python安裝之后,其標(biāo)準(zhǔn)庫中有的模塊,不一定要通過代碼來引用,還可以直接在命令行中使用的。
在命令行中直接使用Python標(biāo)準(zhǔn)庫的模塊,最大的好處就是就是不用寫代碼,就能使用其中的功能,
當(dāng)臨時需要一些某些功能的時候,用這種方式會快捷,方便很多。
1. 命令行中使用模塊
命令行中使用python標(biāo)準(zhǔn)庫的模塊,一般格式如下:
python -m <mod-name> <options>
其中,mod-name 是模塊的名稱;options 是模塊的參數(shù)。
本篇列舉的是我自己在命令行中常用的一些模塊,并不是所有可在命令行中可用的模塊。
其它好用的模塊,歡迎大家推薦。
2. http.server:靜態(tài)文件服務(wù)
http.server 模塊的參數(shù)主要有:
python -m http.server -h
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)
主要的參數(shù):
- 
-b:如果需要讓局域網(wǎng)的其他機(jī)器訪問,可以設(shè)置 
-b 0.0.0.0 - -d:設(shè)置靜態(tài)文件服務(wù)的根目錄
 
創(chuàng)建一個目錄作為靜態(tài)文件服務(wù)的根目錄,并放入一個index.html文件。
html文件內(nèi)容:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>http.server</title>
  </head>
  <body>
    <h1>hello</h1>
    <br />
    <h1>python -m http.server</h1>
  </body>
</html>
啟動服務(wù),效果如下:
python -m http.server -d ./sample-site
3. gzip:壓縮/解壓縮
gzip模塊可用來壓縮,解壓縮文件。
python -m gzip -h
usage: gzip.py [-h] [--fast | --best | -d] [file ...]
A simple command line interface for the gzip module: act like gzip, but do not delete the input file.
positional arguments:
  file
options:
  -h, --help        show this help message and exit
  --fast            compress faster
  --best            compress better
  -d, --decompress  act like gunzip instead of gzip
壓縮文件:
python -m gzip test.txt
# 會生成一個 test.txt.gz 文件
解壓文件(-d 參數(shù)用來解壓):
python -m gzip -d test.txt.gz
# 會解壓出 test.txt 文件
4. base64:編碼解碼文件
當(dāng)我們臨時要用base64來編碼或解碼字符串的時候,可以用這個模塊。
python -m base64 -h
usage: D:\miniconda3\envs\databook\Lib\base64.py [-h|-d|-e|-u|-t] [file|-]
        -h: print this help message and exit
        -d, -u: decode
        -e: encode (default)
        -t: encode and decode string 'Aladdin:open sesame'
用base64編碼一個字符串:
echo "abcdefg" | python -m base64
YWJjZGVmZw0K
解碼base64字符串:用上面編碼后的base64來還原。
echo "YWJjZGVmZw0K" | python -m base64 -d
abcdefg
5. json.tool:更好的顯示json結(jié)構(gòu)
這個工具對于經(jīng)常使用命令行的人來說,非常有用。
從命令行訪問某些API接口的時候,返回的json數(shù)據(jù)往往是壓縮在一行,很難閱讀。
json.tool模塊的參數(shù)很多,但是一般大部分情況下是不需要設(shè)置的,
使用參數(shù)的默認(rèn)值就可以了:
python -m json.tool -h
usage: python -m json.tool [-h] [--sort-keys] [--no-ensure-ascii] [--json-lines]
                           [--indent INDENT | --tab | --no-indent | --compact]
                           [infile] [outfile]
A simple command line interface for json module to validate and pretty-print JSON objects.
positional arguments:
  infile             a JSON file to be validated or pretty-printed
  outfile            write the output of infile to outfile
options:
  -h, --help         show this help message and exit
  --sort-keys        sort the output of dictionaries alphabetically by key
  --no-ensure-ascii  disable escaping of non-ASCII characters
  --json-lines       parse input using the JSON Lines format. Use with --no-indent or --compact to produce valid
                     JSON Lines output.
  --indent INDENT    separate items with newlines and use this number of spaces for indentation
  --tab              separate items with newlines and use tabs for indentation
  --no-indent        separate items with spaces rather than newlines
  --compact          suppress all whitespace separation (most compact)
比如下面的json字符串:
echo '{"code":0,"message":"success""data":[{"name":"harry"},{"name":"joe"}]}' | python -m json.tool
{
    "code": 0,
    "message": "success",
    "data": [
        {
            "name": "harry"
        },
        {
            "name": "joe"
        }
    ]
}
6. calendar:日歷信息
calendar這個模塊相當(dāng)于是個命令行下的日歷。
可以指定某一年的日歷(默認(rèn)是當(dāng)前年的):
python -m calendar 2022
也可以指定某一年某個月的日歷:
python -m calendar 2023 10
這個命令還可以把日歷轉(zhuǎn)換成HTML格式導(dǎo)出,具體可以看它的help信息。
7. ast:顯示代碼的抽象語法數(shù)
這個ast模塊就強(qiáng)大了,它可以將原始的python代碼轉(zhuǎn)換為抽象語法樹。
基于抽象語法樹,可以做一些底層的代碼分析,代碼生成,甚至轉(zhuǎn)換成其它語言的代碼等等。
ast模塊的參數(shù)不多,一般用默認(rèn)參數(shù)即可:
python -m ast -h
usage: python -m ast [-h] [-m {exec,single,eval,func_type}] [--no-type-comments] [-a] [-i INDENT] [infile]
positional arguments:
  infile                the file to parse; defaults to stdin
options:
  -h, --help            show this help message and exit
  -m {exec,single,eval,func_type}, --mode {exec,single,eval,func_type}
                        specify what kind of code must be parsed
  --no-type-comments    don't add information about type comments
  -a, --include-attributes
                        include attributes such as line numbers and column offsets
  -i INDENT, --indent INDENT
                        indentation of nodes (number of spaces)
下面構(gòu)造一個python代碼文件(main.py),內(nèi)容比較簡單,就是一個累加的功能。
# -*- coding: utf-8 -*-
def sum(start, end):
    sum = 0
    for i in range(start, end + 1):
        sum += i
    print("1+2+...+10 = {}".format(sum))
if __name__ == "__main__":
    sum(1, 10)
轉(zhuǎn)換之后的抽象語法樹為:
python -m ast main.py
Module(
   body=[
      FunctionDef(
         name='sum',
         args=arguments(
            posonlyargs=[],
            args=[
               arg(arg='start'),
               arg(arg='end')],
               ...省略...
         body=[
            Assign(
               targets=[
                  Name(id='sum', ctx=Store())],
               value=Constant(value=0)),
            For(
               target=Name(id='i', ctx=Store()),
               ...省略...
               orelse=[]),
            Expr(
               value=Call(
               ...省略...
                  keywords=[]))],
         decorator_list=[]),
      If(
         test=Compare(
               ...省略...
         orelse=[])],
   type_ignores=[])
轉(zhuǎn)換后的內(nèi)容比較長,中間我省略一些內(nèi)容。
對完整的內(nèi)容感興趣,可以自己試試轉(zhuǎn)換一個python代碼文件。
總結(jié)
以上是生活随笔為你收集整理的Python标准库中隐藏的利器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: XREAL 双 11 战报:全网 GMV
 - 下一篇: 一个操作系统的设计与实现——第12章 任