蟒蛇|更改外壳中的文本颜色 [英] Python | change text color in shell

查看:35
本文介绍了蟒蛇|更改外壳中的文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人知道如何设置显示在 shell 中的文本的颜色.我注意到ls"在将信息打印到屏幕上时使用了几种不同的颜色(在我的 Linux 机器上),我想知道我是否可以在 Python 中利用它.

I was wondering if anyone knows how to set the color of the text that shows up in the shell. I noticed the 'ls' uses a couple different colors when printing out information to the screen (on my Linux box), was wondering if I could take advantage of that in Python.

推荐答案

使用 Curses 或 ANSI 转义序列.在开始喷出转义序列之前,您应该检查 stdout 是否为 tty.你可以用 sys.stdout.isatty() 做到这一点.这是一个从我的项目中提取的函数,它根据状态使用 ANSI 转义序列以红色或绿色打印输出:

Use Curses or ANSI escape sequences. Before you start spouting escape sequences, you should check that stdout is a tty. You can do this with sys.stdout.isatty(). Here's a function pulled from a project of mine that prints output in red or green, depending on the status, using ANSI escape sequences:

def hilite(string, status, bold):
    attr = []
    if status:
        # green
        attr.append('32')
    else:
        # red
        attr.append('31')
    if bold:
        attr.append('1')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)

这篇关于蟒蛇|更改外壳中的文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆