zoukankan      html  css  js  c++  java
  • Python 格式化输出 ( 颜色 )


    简介:

    Python 中如果想让输出有颜色显示,实现起来还是挺容易的,你需要拥有 termcolor 的知识!

    参考地址:https://pypi.python.org/pypi/termcolor/1.1.0

    开整:

    shell > pip install termcolor       # 如果没有该模块, 要先安装
    
    shell > ipython # 进入 ipython
    
    In [1]: import termcolor            # 导入该模块
    
    In [2]: termcolor.
    termcolor.ATTRIBUTES termcolor.HIGHLIGHTS termcolor.VERSION termcolor.cprint termcolor.print_function
    termcolor.COLORS termcolor.RESET termcolor.colored termcolor.os

    # 上面是该模块的方法,最常用的方法应该是 .colored 吧

    示例:

    In [1]: from termcolor import colored                                          # 只导入这一个方法,因为别的用不到
    
    In [2]: colored??                                                              # 查看支持哪些参数,当然下面还有程序提供的示例,这里就不贴了
    Signature: colored(text, color=None, on_color=None, attrs=None)
    
    In [3]: text = colored('Hello World', 'red')                                   # 第一个参数是将要输出的文本,第二个参数是设置该文本的颜色
    
    In [4]: print(text)                                                            # 输出红色的 Hello World
    Hello World
    
    In [5]: print(colored('Hello World', 'green'))                                 # 更简单一点,输出绿色的 Hello World
    Hello World
    
    In [6]: code_yellow = lambda x: colored(x, 'yellow')                           # 可以使用匿名函数将颜色抽象出现,方便以后调用
    
    In [7]: print(code_yellow('Hello World'))                                      # 输出黄色的 Hello World
    Hello World
    
    In [8]: print(colored('Hello World', 'red', 'on_yellow'))                      # 输出红色的 Hello World,背景色为黄色
    Hello World
    
    In [9]: print(colored('Hello, World', 'yellow', attrs=['reverse', 'blink']))   # 官方给的说法是代码闪烁,我这没有闪,跟设置背景色一样效果!
    Hello, World
    
    In [10]: print(colored('%s' % 'Hello World', 'red', 'on_yellow'))              # 另外,也是可以输出格式化的,就是 %s % text 这样的方式,还是很方便的!
    Hello World
  • 相关阅读:
    centos7 安装 nginx
    centos 关闭防火墙
    springcloud + nacos + mybatis ,增加seata分布式事务
    docker 运行 seata-server 配置nacos
    分布式事务4种方式,通俗易解篇
    主键字段报错doesn't have a default value (mybatis)
    模拟部署一个前后端分离的项目
    nginx配置接口转发路径
    前端部署后出现白板异常
    nodeJs的升降级(win10下)
  • 原文地址:https://www.cnblogs.com/wangxiaoqiangs/p/5369226.html
Copyright © 2011-2022 走看看