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

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

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

python -m calendar 2023 10

这个命令还可以把日历转换成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标准库中隐藏的利器的更多相关文章

  1. Python 标准库中的装饰器

    题目描述 1.简单举例 Python 标准库中的装饰器 2.说说你用过的 Python 标准库中的装饰器 1. 首先,我们比较熟悉,也是比较常用的 Python 标准库提供的装饰器有:property ...

  2. (转)python标准库中socket模块详解

    python标准库中socket模块详解 socket模块简介 原文:http://www.lybbn.cn/data/datas.php?yw=71 网络上的两个程序通过一个双向的通信连接实现数据的 ...

  3. C++实现python标准库中的Counter

    看python standard library by exmple里面提到一个Counter容器,它像muliset一样,能够维持一个集合,并在常量时间插入元素.查询某个元素的个数,而且还提供了一个 ...

  4. Python标准库中的生成器函数

    一.用于过滤的生成器函数 - 从输入的可迭代对象中产出元素的子集,而不修改元素本身 import itertools l1 = [1,2,3,4,5] l2 = [True,False,True,Fa ...

  5. 06.队列、python标准库中的双端队列、迷宫问题

    class QueueUnderflow(ValueError): """队列为空""" pass class SQueue: def __ ...

  6. python标准库中socket模块详解

    包含原理就是tcp的三次握手 http://www.lybbn.cn/data/datas.php?yw=71 这篇讲到了socket和django的联系 https://www.cnblogs.co ...

  7. python标准库00 学习准备

    Python标准库----走马观花 python有一套很有用的标准库.标准库会随着python解释器一起安装在你的电脑上的.它是python的一个组成部分.这些标准库是python为你准备的利器,可以 ...

  8. Python标准库——走马观花

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python有一套很有用的标准库(standard library).标准库会随着 ...

  9. Python标准库14 数据库 (sqlite3)

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python自带一个轻量级的关系型数据库SQLite.这一数据库使用SQL语言.S ...

  10. python标准库xml.etree.ElementTree的bug

    使用python生成或者解析xml的方法用的最多的可能就数python标准库xml.etree.ElementTree和lxml了,在某些环境下使用xml.etree.ElementTree更方便一些 ...

随机推荐

  1. 【博客索引】Welcome!!

    欢迎来到 Daniel_yzy 的博客园 个人简介 初二,男,就读于长沙市一中双语实验学校. 爱好 OI,一生讨厌文化课. 当然,也是唯物主义无神论者. 已有 npy,要问是谁的话可以私下问. 博客索 ...

  2. springboot整合mqtt 消费端

    用到的工具: EMQX , mqttx , idea 工具使用都很简单,自己看看就能会. 订阅端config代码: package com.example.demo.config; import lo ...

  3. Django: Token分发

    Django后台token分发 在settings.py中引入 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'd ...

  4. 如何在 Windows10 下运行 Tensorflow 的目标检测?

    前言 看过很多博主通过 Object Detection 实现了一些皮卡丘捕捉,二维码检测等诸多特定项的目标检测.而我跟着他们的案例来运行的时候,不是 Tensorflow 版本冲突,就是缺少什么包, ...

  5. ROC 曲线与 PR 曲线

    ROC 曲线与 PR 曲线 ROC 曲线与 PR 曲线 ROC 曲线和 PR 曲线是评估机器学习算法性能的两条重要曲线,两者概念比较容易混淆,但是两者的使用场景是不同的.本文主要讲述两种曲线的含义以及 ...

  6. RobotFrameWork环境搭建及使用

    RF环境搭建 首先安装python并且配置python环境变量 pip install robotframework pip install robotframework-ride 生产桌面快捷方式 ...

  7. .NET Core多线程 (2) 异步 - 上

    去年换工作时系统复习了一下.NET Core多线程相关专题,学习了一线码农老哥的<.NET 5多线程编程实战>课程,我将复习的知识进行了总结形成本专题. 本篇,我们来复习一下异步的相关知识 ...

  8. 使用在线Excel时,有哪些方法可以引入计算函数?

    摘要:本文由葡萄城技术团队于博客园原创并首发.转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者. 前言 在日常生活和工作中,我们都会或多或少的使用Excel中的 ...

  9. Ubuntu安装后续工作

    更新源: sudo gedit /etc/apt/sources.list 清华的源 deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial ma ...

  10. 【干货】华为云图数据库GES技术演进

    本文分享自华为云社区<[干货]华为云图数据库GES技术演进>,作者: Chenyi. 1 背景 大规模图数据无处不在,图查询.分析和表示学习已成为大数据和AI的核心部分之一.特别是知识图谱 ...