简体   繁体   English

如何打印彩色 ANSI 字符?

[英]How do I print colored ANSI characters?

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.我正在使用 Flask 和 flask_restful 开发 API,并为我正在从事的项目开发匹配的 CLI,现在遇到了一些我无法摆脱的事情。 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.在 API 方面,当我在某个端点上收到请求时,我使用PrettyTable库在终端上构建彩色表。 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.我试图返回t对象,但它不是 JSON 可序列化的。 By calling the __str__ method I was able to return it successfully, but just can't print the output properly on my terminal.通过调用__str__方法,我能够成功返回它,但无法在我的终端上正确打印输出。 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?你们能帮我做对吗?

Well, I found a way of fixing it.嗯,我找到了修复它的方法。 On the API side, I turn the response into JSON by doing:在 API 方面,我通过执行以下操作将响应转换为 JSON:

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

instead of my previous return t.__str__() .而不是我之前的return t.__str__()

After that, on the CLI, I do:之后,在 CLI 上,我执行以下操作:

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

and it works like a charm!它就像一个魅力!

Thanks everybody.谢谢大家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM