Code example sharing of Python colorized Linux command line terminal interface

WBOY
Release: 2016-07-22 08:56:34
Original
1287 people have browsed it

先看看效果:

201672120703121.jpg (251×123)

在linux的终端中,ANSI转义序列来控制颜色
基本规则: 前面加上\033[,结尾用\033[0m重置为原来的颜色
可以在终端中输入下面这句,就可以看到输出绿色的hello。

>>echo -e '\033[0;32mhello\033[0m'
Copy after login

其中0;32m控制颜色。
最简单的,只要把0;32m中的2改成0-7,就对应不同颜色了。

利用这点,在python中,可以这样来。

#coding=utf-8 
fmt = '\033[0;3{}m{}\033[0m'.format 
class color: 
  BLACK = 0#黑 
  RED  = 1#红 
  GREEN = 2#绿 
  YELLOW = 3#棕 
  BLUE  = 4#蓝 
  PURPLE = 5#紫 
  CYAN  = 6#青 
  GRAY  = 7#灰 
 
print fmt(color.BLACK ,'kzc') 
print fmt(color.RED  ,'kzc') 
print fmt(color.GREEN ,'kzc') 
print fmt(color.YELLOW ,'kzc') 
print fmt(color.BLUE  ,'kzc') 
print fmt(color.PURPLE ,'kzc') 
print fmt(color.CYAN  ,'kzc') 
print fmt(color.GRAY  ,'kzc') 

Copy after login

PS:Linux下优雅地执行程序
在linux下,我们执行一个python程序是python /path/to/xxx.py。
如果这个程序经常使用,会觉得这样有点麻烦。
可以chmod +x /path/to/xxx.py,即给这个文件加上了可执行权限,就可以不用在前面敲python,直接/path/to/xxx.py运行了。
不过,对于有代码洁癖的人看来,这样还不够优雅,后面还带着.py后缀。
把.py后缀去掉也行,只要在文件的第一行加上#!/usr/bin/python。
然后直接/path/to/xxx就能执行了。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!