Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pretty table with color output

I am using pretty table to generate tables output.

Is it possible to generate in terms of colors. If failed it should display in red and its ok it should display in green.

Code:

from prettytable import PrettyTable
a = "ok"
b = "Failed"
t = PrettyTable(['Input', 'status'])
if a == "ok":
   t.add_row(['FAN', a])
else:
    t.add_row(['FAN', b])
print t  
like image 258
meteor23 Avatar asked Apr 24 '17 09:04

meteor23


People also ask

How do you color a table in Python?

Coloured Text in the Console with The Python Colorama Module To use this module you will need to intsall with pip instal colorama . You can find the module along with documentation here: Colorama. Below is a basic example of its usage.

How do I print a pretty table in Python?

Two libraries provide the functionality to pretty print comma-separated values (CSV) in Python: tabulate and prettytable. These don't come standard with Python, so you have to install them with a quick pip install command.

How do I download Prettytable Python?

Download the latest version of PrettyTable from the Downloads tab at this Google code project site. Save the file as "prettytable.py" (not prettytable-x.y.py) in your Python installation's "site-packages" directory.

What is a pretty table?

PrettyTable is a Python library that is used to represent tabular data in visually appealing ASCII tables. It is quick and easy to use.


Video Answer


2 Answers

Here is an example of an easy way to add colour in table.

from prettytable import PrettyTable

#Color
R = "\033[0;31;40m" #RED
G = "\033[0;32;40m" # GREEN
Y = "\033[0;33;40m" # Yellow
B = "\033[0;34;40m" # Blue
N = "\033[0m" # Reset


a = "ok"
b = "Failed"
t = PrettyTable(['Input', 'status'])

#Adding Both example in table
t.add_row(['FAN', G+a+N])
t.add_row(['FAN', R+b+N])

print t
like image 77
TouhidShaikh Avatar answered Oct 07 '22 01:10

TouhidShaikh


here we go

from prettytable import PrettyTable
a = "ok"
b = "Failed"
t = PrettyTable(['Input', 'status'])
if a == "ok":
  a = "\033[1;32m%s\033[0m" %a 
  t.add_row(['FAN', a])
else:
  b = "\033[1;31m%s\033[0m" %b
  t.add_row(['FAN', b])
print t  
like image 22
L.kifa Avatar answered Oct 07 '22 01:10

L.kifa