开发者

How to display ANSI colors in python script output running on Unix

开发者 https://www.devze.com 2023-02-14 18:43 出处:网络
I have a simple Python script that uses ANSI escape sequences to开发者_JS百科 have colored output on the terminal.

I have a simple Python script that uses ANSI escape sequences to开发者_JS百科 have colored output on the terminal.

And this works great, but when the output is being used elsewhere (for example in VIM) all the ANSI sequences show up and it makes it really unreadable.

For example, to display RED I do something like:

^[[91m Errors:
-------^[[0m

Which is perfectly readable in the terminal.

I could add a flag to my Python command line tool to avoid displaying these characters when I need to deal with output, but I was wondering if there is a way of having colored output without messing up output.

The solution would have to use the Python Stdlib or would have to avoid installing a third party library.

However, I am perfectly OK if the approach doesn't work on Windows :)


You can use os.isatty with the stdout file descriptor, which can be retrieved by calling fileno on sys.stdout.

Edit: It looks like files also have an isatty method; therefore, you can avoid using the os module and just using sys.stdout.isatty().


Look at this answer it covers exactly what you are asking for

How do I detect whether sys.stdout is attached to terminal or not?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号