经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
Python标准库中隐藏的利器
来源:cnblogs  作者:wang_yb  时间:2023/11/13 8:45:52  对本文有异议

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)

主要的参数:

  1. -b:如果需要让局域网的其他机器访问,可以设置 -b 0.0.0.0
  2. -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

image.png

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

image.png

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

  1. python -m calendar 2023 10

image.png

这个命令还可以把日历转换成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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号