使用特殊字符实现console UI
发布时间:2020-12-14 01:33:23 所属栏目:Linux 来源:网络整理
导读:我们经常见到一些开源软件在安装或运行时,实现了某种程度上的基于Linux命令行终端的界面,使我们可以更直观的感受软件运行情况或进度, 例如下面的测试进度变化: 使用Python时,我们可以通过print()函数和某些特殊字符达到上面的效果。 先看一下Python的pr
我们经常见到一些开源软件在安装或运行时,实现了某种程度上的基于Linux命令行终端的界面,使我们可以更直观的感受软件运行情况或进度, 例如下面的测试进度变化: 使用Python时,我们可以通过print()函数和某些特殊字符达到上面的效果。 先看一下Python的print()函数定义:从下面的帮助文档,我们可以看到print()有4个关键字参数: sep,end,file,flush,其中sep表示当打印多个参数时,各参数间的分隔符,默认为一个空格;end表示一次打印结束时添加的结尾标识符,默认为换行符;file为类似文件的字节流对象,默认为sys.stdout; flush 指示是否强制将缓冲区数据写入输出设备,对于sys.stdout来讲,就是显示器。 print(...) print(value,...,sep=‘ ‘,end=‘n‘,file=sys.stdout,flush=False) Prints the values to a stream,or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values,default a space. end: string appended after the last value,default a newline. flush: whether to forcibly flush the stream. 再看一下转义字符‘r‘,该字符使的输入位置重新回到本行开头。利用print()的end参数和‘r‘,我们可以实现一个的进度条: 代码如下: import time for i in range(1,11): percent = i * 10 if i < 10: bar = ‘[‘ + ‘=‘ * (i * 5) + ‘>]‘ print(‘{}% {}r‘.format(percent,bar),end=‘‘) else: bar = ‘[‘ + ‘=‘ * (i * 5) + ‘]‘ print(‘{}% {}r‘.format(percent,bar)) time.sleep(1) ? 我们也可以使用特定的字符组合控制输出的颜色, 例如 代码如下: #utils/textcolor.py class TextColor: NONE = " |