Python标准库中有哪些好用的模块

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: 在命令行中使用Python标准库模块,如`http.server`、`gzip`、`base64`、`json.tool`和`calendar`,可以直接通过`python -m module_name`调用,无需额外编写代码。例如,`python -m http.server`启动一个简单的HTTP服务器,`python -m gzip -d file.gz`解压缩文件。`json.tool`用于美化显示JSON数据,而`calendar`模块则能输出日历信息。这些在临时需要相关功能时特别方便。

在命令行中直接使用Python标准库的模块,最大的好处就是就是不用写代码,就能使用其中的功能,

当临时需要一些某些功能的时候,用这种方式会快捷,方便很多。

1. 命令行中使用模块

命令行中使用python标准库的模块,一般格式如下:

bash

复制代码

python -m <mod-name> <options>

其中,mod-name 是模块的名称;options 是模块的参数。

本篇列举的是我自己在命令行中常用的一些模块,并不是所有可在命令行中可用的模块。

其它好用的模块,欢迎大家推荐。

2. http.server:静态文件服务

http.server 模块的参数主要有:

bash

复制代码

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文件内容:

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>

启动服务,效果如下:

bash

复制代码

python -m http.server -d ./sample-site

3. gzip:压缩/解压缩

gzip模块可用来压缩,解压缩文件。

bash

复制代码

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

压缩文件:

bash

复制代码

python -m gzip test.txt

# 会生成一个 test.txt.gz 文件

解压文件(-d 参数用来解压):

bash

复制代码

python -m gzip -d test.txt.gz

# 会解压出 test.txt 文件

4. base64:编码解码文件

当我们临时要用base64来编码或解码字符串的时候,可以用这个模块。

bash

复制代码

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编码一个字符串:

bash

复制代码

echo "abcdefg" | python -m base64

YWJjZGVmZw0K

解码base64字符串:用上面编码后的base64来还原。

bash

复制代码

echo "YWJjZGVmZw0K" | python -m base64 -d

abcdefg

5. json.tool:更好的显示json结构

这个工具对于经常使用命令行的人来说,非常有用。

从命令行访问某些API接口的时候,返回的json数据往往是压缩在一行,很难阅读。

json.tool模块的参数很多,但是一般大部分情况下是不需要设置的,

使用参数的默认值就可以了:

bash

复制代码

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字符串:

bash

复制代码

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这个模块相当于是个命令行下的日历。

可以指定某一年的日历(默认是当前年的):

bash

复制代码

python -m calendar 2022

也可以指定某一某个的日历:

bash

复制代码

python -m calendar 2023 10

这个命令还可以把日历转换成HTML格式导出,具体可以看它的help信息

7. ast:显示代码的抽象语法数

这个ast模块就强大了,它可以将原始的python代码转换为抽象语法树

基于抽象语法树,可以做一些底层的代码分析,代码生成,甚至转换成其它语言的代码等等。

ast模块的参数不多,一般用默认参数即可:

bash

复制代码

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),内容比较简单,就是一个累加的功能。

python

复制代码

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

转换之后的抽象语法树为:

bash

复制代码

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代码文件。


转载来源:https://juejin.cn/post/7299346813262528512

相关文章
|
3月前
|
开发者 Python
如何在Python中管理模块和包的依赖关系?
在实际开发中,通常会结合多种方法来管理模块和包的依赖关系,以确保项目的顺利进行和可维护性。同时,要及时更新和解决依赖冲突等问题,以保证代码的稳定性和可靠性
147 62
|
2月前
|
Python
Python Internet 模块
Python Internet 模块。
129 74
|
3月前
|
算法 数据安全/隐私保护 开发者
马特赛特旋转算法:Python的随机模块背后的力量
马特赛特旋转算法是Python `random`模块的核心,由松本真和西村拓士于1997年提出。它基于线性反馈移位寄存器,具有超长周期和高维均匀性,适用于模拟、密码学等领域。Python中通过设置种子值初始化状态数组,经状态更新和输出提取生成随机数,代码简单高效。
133 63
|
3月前
|
数据可视化 Python
如何在Python中解决模块和包的依赖冲突?
解决模块和包的依赖冲突需要综合运用多种方法,并且需要团队成员的共同努力和协作。通过合理的管理和解决冲突,可以提高项目的稳定性和可扩展性
|
3月前
|
测试技术 Python
手动解决Python模块和包依赖冲突的具体步骤是什么?
需要注意的是,手动解决依赖冲突可能需要一定的时间和经验,并且需要谨慎操作,避免引入新的问题。在实际操作中,还可以结合使用其他方法,如虚拟环境等,来更好地管理和解决依赖冲突😉。
|
28天前
|
Python
[oeasy]python057_如何删除print函数_dunder_builtins_系统内建模块
本文介绍了如何删除Python中的`print`函数,并探讨了系统内建模块`__builtins__`的作用。主要内容包括: 1. **回忆上次内容**:上次提到使用下划线避免命名冲突。 2. **双下划线变量**:解释了双下划线(如`__name__`、`__doc__`、`__builtins__`)是系统定义的标识符,具有特殊含义。
29 3
|
3月前
|
持续交付 Python
如何在Python中自动解决模块和包的依赖冲突?
完全自动解决所有依赖冲突可能并不总是可行,特别是在复杂的项目中。有时候仍然需要人工干预和判断。自动解决的方法主要是提供辅助和便捷,但不能完全替代人工的分析和决策😉。
|
3月前
|
Python
Python的模块和包
总之,模块和包是 Python 编程中非常重要的概念,掌握它们可以帮助我们更好地组织和管理代码,提高开发效率和代码质量
92 36
|
3月前
|
JavaScript 前端开发 Python
python中的OS模块的基本使用
欢迎来到瑞雨溪的博客,一名热爱JavaScript与Vue的大一学生。博客分享前端技术及全栈开发经验,持续更新中,期待您的关注和支持!🎉🎉🎉
50 0
|
3月前
|
JavaScript 前端开发 Python
python中的platform模块的基本使用
欢迎来到瑞雨溪的博客,一名热爱JavaScript与Vue的大一学生。博客分享前端技术,助你成长。关注我,持续更新中!🎉🎉🎉
42 0