首页 > 编程语言 >Python标准库中隐藏的利器

Python标准库中隐藏的利器

时间:2023-11-12 09:57:53浏览次数:29  
标签:库中 Python base64 python 利器 json 模块 -- help

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

标签:库中,Python,base64,python,利器,json,模块,--,help
From: https://www.cnblogs.com/wang_yb/p/17826783.html

相关文章

  • Python 潮流周刊#26:requests3 的现状
    你好,我是猫哥。这里每周分享优质的Python、AI及通用技术内容,大部分为英文。本周刊开源,欢迎投稿。另有电报频道作为副刊,补充发布更加丰富的资讯。......
  • 一篇文章带你了解Python基础测试工具——UnitTest
    一篇文章带你了解Python基础测试工具——UnitTest测试人员一般使用Python作为主语言脚本来进行自动化开发,而Python自带的UnitTest脚本通常就是测试人员首先掌握的那么本篇文章我们将来介绍Python的最基本自动化工具UnitTest来开始我们自动化的第一步我们这篇文章将从以下角度进......
  • python中BeautifulSoup库使用小结
    转载请注明出处:BeautifulSoup是一个用于解析HTML和XML文档的Python库,它提供了一些简单但强大的API,让你可以从文档中提取数据。以下是一些BeautifulSoup的主要特性和功能:解析HTML和XML文档:BeautifulSoup可以解析HTML和XML文档,并创建一个BeautifulSoup对象,这个对象表示整个......
  • python rpy2.robjects库总结
    参考:https://rpy2.github.io/介绍rpy2是用C语言编写的,是嵌入在Python进程中的R运行接口。该包由几个子包或模块组成:1)rpy2.rinterface:R的低级接口,当速度和灵活性最重要的时候。接近R的c级API。2)rpy2.robjects:R的高级接口,注重易用性。更友好,使用更广泛。3)rpy2.interactive......
  • pythonDay10
    X模式,是只写模式,文件存在时则会报错,文件不存在则创建文件换行:r\  n\b模式案例及循环补充 flush刷新,只出现在测试场景 文件指针移动 ......
  • 【Python | 虚拟环境】Python创建虚拟环境哪些事,一文打通脉络,确定不来看看?
    ......
  • python中包管理工具pip以及虚拟环境venv的使用
    1.pip命令查看已安装的包piplist安装包pipinstallpackage_name卸载包#卸载指定包pipuninstallpackage_name#卸载已安装的所有第三方Python库pipfreeze>list.txtpipuninstall-rlist.txt-y导出已安装的包pipfreeze>requirements.txt配置全局默......
  • Python 数据解析:从基础到高级技巧
    导言:Python作为一门强大的编程语言,不仅在Web开发、数据分析和人工智能领域有广泛的应用,还在数据解析方面具有强大的能力。数据解析是从结构化或非结构化数据源中提取有用信息的过程,通常在数据清洗、数据分析和可视化之前进行。本文将深入探讨Python在数据解析中的应用,从基础知识到......
  • wechaty撸一个属于自己的微信机器人(Python版接入文心一言)
    前言说明:机器人的框架找了很久,由于很多框架都不能使用了或者封号率极高,最后选择了wewechaty,wechaty是可以使用ipad协议,主要是以node写的,因为打算机器人接入爬虫项目,所以特意用了python版本,对于python版网上教程太少且模糊且时间过于久远,所做以此文为采坑记录。前期准备:tok......
  • tensorflow版本与CUDA、cuDNN、Python适配表
    从源代码构建 | TensorFlow(google.cn)......