Python標準庫中隱藏的利器

来源:https://www.cnblogs.com/wang_yb/archive/2023/11/12/17826783.html
-Advertisement-
Play Games

Python安裝之後,其標準庫中有的模塊,不一定要通過代碼來引用,還可以直接在命令行中使用的。 在命令行中直接使用Python標準庫的模塊,最大的好處就是就是不用寫代碼,就能使用其中的功能,當臨時需要一些某些功能的時候,用這種方式會快捷,方便很多。 1. 命令行中使用模塊 命令行中使用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

image.png

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

image.png

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

python -m calendar 2023 10

image.png

這個命令還可以把日曆轉換成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代碼文件。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 常見鎖介紹 synchronized鎖的八中情況 package com.shaonian.juc.more_thread_lock; import java.util.concurrent.TimeUnit; class Phone { public static synchronized voi ...
  • Python MySQL 限制結果 限制結果數量 示例 1: 獲取您自己的 Python 伺服器 選擇 "customers" 表中的前 5 條記錄: import mysql.connector mydb = mysql.connector.connect( host="localhost", u ...
  • 操作系統 :Windows 10_x64 python版本 :3.9.2 pymysql版本: 1.0.2 MySQL版本: 5.7.38 之前寫過一篇關於python操作mysql資料庫的文章: https://www.cnblogs.com/MikeZhang/p/pythonOptMysql2 ...
  • 寫在前面 目前已經上班快兩個月了,對現在的工作很滿意,甚至更喜歡這的氛圍吧。 如題所示,從今年5月開始,發生的所有事,都完全超出了我自己可以承受的範圍,好在這一切都過去了,真的感謝上天安排,讓我能更加確信自己要的是什麼,以後該怎麼生活。 爸爸被診斷為肺癌 我每年都會帶父母去做體檢,因為去年疫情全面放 ...
  • 本文適用範圍 主要適用於debug python 程式,尤其是深度學習剛入門需要使用remote 連接到linux進行程式運行,想調試一下的同學。 當然非深度學習也可以參考食用本文哈哈哈。 極速入門版 提前準備:代碼倉庫已經拉取到linux上面,且已經知道運行的方式。 比如: 項目的啟動命令為:py ...
  • 五、位運算 ​ 位運算主要計算記憶體中每個小格的數據 1、輸出二進位內容 頭文件調用 語法 示例 include <bitser> std::bitset<要顯示的二進位位數>(要顯示的變數) std::cout << std::bitset<16>(a); //二進位內容輸出 #include <i ...
  • 在 Java 中,有四種方法可以獲取當前正在執行方法體的方法名稱,分別是: 使用 Thread.currentThread().getStackTrace() 方法 使用異常對象的 getStackTrace() 方法 使用匿名內部類的 getClass().getEnclosingMethod() ...
  • Guava 是 Google 提供的一套 Java 工具包,而 Guava Cache 是該工具包中提供的一套完善的 JVM 級別高併發緩存框架;本文主要介紹它的相關功能及基本使用,文中所使用到的軟體版本:Java 1.8.0_341、Guava 32.1.3-jre。 1、簡介 緩存在很多情況下非 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...