How do I print colored ANSI characters?

Gabriel Milan :

I'm developing an API with Flask and flask_restful and a matching CLI for a project I'm working on and have now faced something I can't get rid of. On the API side, when I get a request on a certain endpoint, I use the PrettyTable library for building a colored table on terminal. I'm building the table as follows:

t = PrettyTable([ Color.CGREEN2 + 'Username' + Color.CEND,
                  Color.CGREEN2 + 'Dataset'  + Color.CEND,
                  Color.CGREEN2 + 'Files' + Color.CEND])
for ds in db.getAllDatasets( username ):
  t.add_row(  [username, ds.dataset, len(ds.files)] )
return t.__str__()

I've tried to return the t object, but it wasn't JSON serializable. By calling the __str__ method I was able to return it successfully, but just can't print the output properly on my terminal. The code I'm using for that is:

try:
  r = requests.post(url='http://my-server:my-port/my-endpoint', data=data)
  print (str(r.text))
except requests.exceptions.ConnectionError:
  MSG_ERROR (self, "Failed to connect to LPS Cluster.")

And the output I get is:

"+----------+---------+-------+\n| \u001b[92mUsername\u001b[0m | \u001b[92mDataset\u001b[0m | \u001b[92mFiles\u001b[0m |\n+----------+---------+-------+\n+----------+---------+-------+"

It's possible to see that the characters are on the right place and it should work, but it doesn't.

I guess it may have something to do with those quotation marks both on beginning and ending of the string, but I'm not sure and don't know what to do about it.

Can you guys help me get it right?

Gabriel Milan :

Well, I found a way of fixing it. On the API side, I turn the response into JSON by doing:

return jsonify(
    error_code=HTTPStatus.OK,
    message=t.get_string()
)

instead of my previous return t.__str__().

After that, on the CLI, I do:

print (r.json()['message'])

and it works like a charm!

Thanks everybody.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18517&siteId=1