翼度科技»论坛 编程开发 python 查看内容

Python标准库中隐藏的利器

8

主题

8

帖子

24

积分

新手上路

Rank: 1

积分
24
Python安装之后,其标准库中有的模块,不一定要通过代码来引用,还可以直接在命令行中使用的。
在命令行中直接使用Python标准库的模块,最大的好处就是就是不用写代码,就能使用其中的功能,
当临时需要一些某些功能的时候,用这种方式会快捷,方便很多。
1. 命令行中使用模块

命令行中使用python标准库的模块,一般格式如下:
  1. python -m <mod-name> <options>
复制代码
其中,mod-name 是模块的名称;options 是模块的参数。
本篇列举的是我自己在命令行中常用的一些模块,并不是所有可在命令行中可用的模块。
其它好用的模块,欢迎大家推荐。
2. http.server:静态文件服务

http.server 模块的参数主要有:
  1. python -m http.server -h
  2. usage: server.py [-h] [--cgi] [-b ADDRESS] [-d DIRECTORY] [-p VERSION] [port]
  3. positional arguments:
  4.   port                  bind to this port (default: 8000)
  5. options:
  6.   -h, --help            show this help message and exit
  7.   --cgi                 run as CGI server
  8.   -b ADDRESS, --bind ADDRESS
  9.                         bind to this address (default: all interfaces)
  10.   -d DIRECTORY, --directory DIRECTORY
  11.                         serve this directory (default: current directory)
  12.   -p VERSION, --protocol VERSION
  13.                         conform to this HTTP version (default: HTTP/1.0)
复制代码
主要的参数:

  • -b:如果需要让局域网的其他机器访问,可以设置 -b 0.0.0.0
  • -d:设置静态文件服务的根目录
创建一个目录作为静态文件服务的根目录,并放入一个index.html文件。
html文件内容:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.   <head>
  4.     <meta charset="UTF-8" />
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6.     <title>http.server</title>
  7.   </head>
  8.   <body>
  9.     <h1>hello</h1>
  10.     <br />
  11.     <h1>python -m http.server</h1>
  12.   </body>
  13. </html>
复制代码
启动服务,效果如下:
  1. python -m http.server -d ./sample-site
复制代码

3. gzip:压缩/解压缩

gzip模块可用来压缩,解压缩文件。
  1. python -m gzip -h
  2. usage: gzip.py [-h] [--fast | --best | -d] [file ...]
  3. A simple command line interface for the gzip module: act like gzip, but do not delete the input file.
  4. positional arguments:
  5.   file
  6. options:
  7.   -h, --help        show this help message and exit
  8.   --fast            compress faster
  9.   --best            compress better
  10.   -d, --decompress  act like gunzip instead of gzip
复制代码
压缩文件:
  1. python -m gzip test.txt
  2. # 会生成一个 test.txt.gz 文件
复制代码
解压文件(-d 参数用来解压):
  1. python -m gzip -d test.txt.gz
  2. # 会解压出 test.txt 文件
复制代码
4. base64:编码解码文件

当我们临时要用base64来编码或解码字符串的时候,可以用这个模块。
  1. python -m base64 -h
  2. usage: D:\miniconda3\envs\databook\Lib\base64.py [-h|-d|-e|-u|-t] [file|-]
  3.         -h: print this help message and exit
  4.         -d, -u: decode
  5.         -e: encode (default)
  6.         -t: encode and decode string 'Aladdin:open sesame'
复制代码
用base64编码一个字符串:
  1. echo "abcdefg" | python -m base64
  2. YWJjZGVmZw0K
复制代码
解码base64字符串:用上面编码后的base64来还原。
  1. echo "YWJjZGVmZw0K" | python -m base64 -d
  2. abcdefg
复制代码
5. json.tool:更好的显示json结构

这个工具对于经常使用命令行的人来说,非常有用。
从命令行访问某些API接口的时候,返回的json数据往往是压缩在一行,很难阅读。
json.tool模块的参数很多,但是一般大部分情况下是不需要设置的,
使用参数的默认值就可以了:
  1. python -m json.tool -h
  2. usage: python -m json.tool [-h] [--sort-keys] [--no-ensure-ascii] [--json-lines]
  3.                            [--indent INDENT | --tab | --no-indent | --compact]
  4.                            [infile] [outfile]
  5. A simple command line interface for json module to validate and pretty-print JSON objects.
  6. positional arguments:
  7.   infile             a JSON file to be validated or pretty-printed
  8.   outfile            write the output of infile to outfile
  9. options:
  10.   -h, --help         show this help message and exit
  11.   --sort-keys        sort the output of dictionaries alphabetically by key
  12.   --no-ensure-ascii  disable escaping of non-ASCII characters
  13.   --json-lines       parse input using the JSON Lines format. Use with --no-indent or --compact to produce valid
  14.                      JSON Lines output.
  15.   --indent INDENT    separate items with newlines and use this number of spaces for indentation
  16.   --tab              separate items with newlines and use tabs for indentation
  17.   --no-indent        separate items with spaces rather than newlines
  18.   --compact          suppress all whitespace separation (most compact)
复制代码
比如下面的json字符串:
  1. echo '{"code":0,"message":"success""data":[{"name":"harry"},{"name":"joe"}]}' | python -m json.tool
  2. {
  3.     "code": 0,
  4.     "message": "success",
  5.     "data": [
  6.         {
  7.             "name": "harry"
  8.         },
  9.         {
  10.             "name": "joe"
  11.         }
  12.     ]
  13. }
复制代码
6. calendar:日历信息

calendar这个模块相当于是个命令行下的日历。
可以指定某一年的日历(默认是当前年的):
  1. python -m calendar 2022
复制代码

也可以指定某一某个的日历:
  1. python -m calendar 2023 10
复制代码

这个命令还可以把日历转换成HTML格式导出,具体可以看它的help信息
7. ast:显示代码的抽象语法数

这个ast模块就强大了,它可以将原始的python代码转换为抽象语法树
基于抽象语法树,可以做一些底层的代码分析,代码生成,甚至转换成其它语言的代码等等。
ast模块的参数不多,一般用默认参数即可:
  1. python -m ast -h
  2. usage: python -m ast [-h] [-m {exec,single,eval,func_type}] [--no-type-comments] [-a] [-i INDENT] [infile]
  3. positional arguments:
  4.   infile                the file to parse; defaults to stdin
  5. options:
  6.   -h, --help            show this help message and exit
  7.   -m {exec,single,eval,func_type}, --mode {exec,single,eval,func_type}
  8.                         specify what kind of code must be parsed
  9.   --no-type-comments    don't add information about type comments
  10.   -a, --include-attributes
  11.                         include attributes such as line numbers and column offsets
  12.   -i INDENT, --indent INDENT
  13.                         indentation of nodes (number of spaces)
复制代码
下面构造一个python代码文件(main.py),内容比较简单,就是一个累加的功能。
  1. # -*- coding: utf-8 -*-
  2. def sum(start, end):
  3.     sum = 0
  4.     for i in range(start, end + 1):
  5.         sum += i
  6.     print("1+2+...+10 = {}".format(sum))
  7. if __name__ == "__main__":
  8.     sum(1, 10)
复制代码
转换之后的抽象语法树为:
  1. python -m ast main.py
  2. Module(
  3.    body=[
  4.       FunctionDef(
  5.          name='sum',
  6.          args=arguments(
  7.             posonlyargs=[],
  8.             args=[
  9.                arg(arg='start'),
  10.                arg(arg='end')],
  11.                ...省略...
  12.          body=[
  13.             Assign(
  14.                targets=[
  15.                   Name(id='sum', ctx=Store())],
  16.                value=Constant(value=0)),
  17.             For(
  18.                target=Name(id='i', ctx=Store()),
  19.                ...省略...
  20.                orelse=[]),
  21.             Expr(
  22.                value=Call(
  23.                ...省略...
  24.                   keywords=[]))],
  25.          decorator_list=[]),
  26.       If(
  27.          test=Compare(
  28.                ...省略...
  29.          orelse=[])],
  30.    type_ignores=[])
复制代码
转换后的内容比较长,中间我省略一些内容。
对完整的内容感兴趣,可以自己试试转换一个python代码文件。

来源:https://www.cnblogs.com/wang_yb/p/17826783.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具