日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

Python标准库中隐藏的利器

發布時間:2023/11/12 C# 69 coder
生活随笔 收集整理的這篇文章主要介紹了 Python标准库中隐藏的利器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python安裝之后,其標準庫中有的模塊,不一定要通過代碼來引用,還可以直接在命令行中使用的。

在命令行中直接使用Python標準庫的模塊,最大的好處就是就是不用寫代碼,就能使用其中的功能,
當臨時需要一些某些功能的時候,用這種方式會快捷,方便很多。

1. 命令行中使用模塊

命令行中使用python標準庫的模塊,一般格式如下:

python -m <mod-name> <options>

其中,mod-name 是模塊的名稱;options 是模塊的參數。

本篇列舉的是我自己在命令行中常用的一些模塊,并不是所有可在命令行中可用的模塊。
其它好用的模塊,歡迎大家推薦。

2. http.server:靜態文件服務

http.server 模塊的參數主要有:

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)

主要的參數:

  1. -b:如果需要讓局域網的其他機器訪問,可以設置 -b 0.0.0.0
  2. -d:設置靜態文件服務的根目錄

創建一個目錄作為靜態文件服務的根目錄,并放入一個index.html文件。
html文件內容:

<!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>

啟動服務,效果如下:

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 參數用來解壓):

python -m gzip -d test.txt.gz

# 會解壓出 test.txt 文件

4. base64:編碼解碼文件

當我們臨時要用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結構

這個工具對于經常使用命令行的人來說,非常有用。
從命令行訪問某些API接口的時候,返回的json數據往往是壓縮在一行,很難閱讀。

json.tool模塊的參數很多,但是一般大部分情況下是不需要設置的,
使用參數的默認值就可以了:

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這個模塊相當于是個命令行下的日歷。
可以指定某一年的日歷(默認是當前年的):

python -m calendar 2022

也可以指定某一某個的日歷:

python -m calendar 2023 10

這個命令還可以把日歷轉換成HTML格式導出,具體可以看它的help信息

7. ast:顯示代碼的抽象語法數

這個ast模塊就強大了,它可以將原始的python代碼轉換為抽象語法樹
基于抽象語法樹,可以做一些底層的代碼分析,代碼生成,甚至轉換成其它語言的代碼等等。

ast模塊的參數不多,一般用默認參數即可:

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)

下面構造一個python代碼文件(main.py),內容比較簡單,就是一個累加的功能。

# -*- 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)

轉換之后的抽象語法樹為:

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=[])

轉換后的內容比較長,中間我省略一些內容。
對完整的內容感興趣,可以自己試試轉換一個python代碼文件。

總結

以上是生活随笔為你收集整理的Python标准库中隐藏的利器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。