Python风骚的打印
大家平时在Linux/Windows下安装软件时,经常会出现进度条和百分比的提示,Python是否能实现这样的打印?安装过程中,经常会看到很多带颜色的安装说明,我们在python输出时,确是千篇一律的黑底白色,是否想过打印的炫酷一些呢?
作其实很简单,今天就来教教大家,通过几分钟的学习让之后代码的输出变得与众不同!
Python打印进度条
python打印进度条的原理其实很简单,先让我们看一个例子吧:
1# -*- coding: utf-8 -*-
2# @Author : 王翔
3# @WeChat : King_Uranus
4# @公众号 : 清风Python
5# @Date : 2019/9/16 22:09
6# @Software : PyCharm
7# @version :Python 3.7.3
8# @File : ProgressBar.py
9
10import time
11
12def progress_bar(total):
13 if total <= 0:
14 raise ValueError("Wrong total number ...")
15 # step = (100 // total if total <= 100 else total // 100)
16
17 for i in range(0, total):
18 time.sleep(0.05)
19 step = int(100 / total * (i + 1))
20 str1 = '
[%3d%%] %s' % (step, '>' * step)
21 print(str1, end='', flush=True)
22
23progress_bar(20)
24print()
25progress_bar(110)
打印进度条
我们通过自己实现了进度条的展示,那么python是否具备现成的模块呢?答案是Yes! tqdm
Tqdm 是一个快速,可扩展的Python进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器 tqdm(iterator)。
安装:pip install tqdm
来看一个例子:
1from tqdm import tqdm
2import string
3import time
4
5for char in tqdm(string.ascii_uppercase):
6 time.sleep(0.1)
7
8for i in tqdm(range(50)):
9 time.sleep(0.05)
tqdm进度条
tqdm的强大远不止此,喜欢的朋友可以去它的git网址详细学习:https://github.com/tqdm/tqdm
Python带色彩输出
python颜色输出其实只是调用了命令号的相关特殊标记,shell中我们也经常使用它:
1print(' 33[30m打印前景色0 33[0m')
2print(' 33[31m打印前景色1 33[0m')
3print(' 33[32m打印前景色2 33[0m')
4print(' 33[33m打印前景色3 33[0m')
5print(' 33[34m打印前景色4 33[0m')
6print(' 33[35m打印前景色5 33[0m')
7print(' 33[36m打印前景色6 33[0m')
8print(' 33[37m打印前景色7 33[0m')
9print(' 33[40m打印背景色0 33[0m')
10print(' 33[41m打印背景色1 33[0m')
11print(' 33[42m打印背景色2 33[0m')
12print(' 33[43m打印背景色3 33[0m')
13print(' 33[44m打印背景色4 33[0m')
14print(' 33[45m打印背景色5 33[0m')
15print(' 33[46m打印背景色6 33[0m')
16print(' 33[47m打印背景色7 33[0m')
17print(' 33[0m打印显示方式0 33[0m')
18print(' 33[1m打印显示方式1 33[0m')
19print(' 33[4m打印显示方式4 33[0m')
20print(' 33[5m打印显示方式5 33[0m')
21print(' 33[7m打印显示方式7 33[0m')
22print(' 33[8m打印显示方式8 33[0m')
23print(' 33[5;31;47m综合打印 33[0m')
颜色类型打印
每条默认的