如何检测控制台是否支持 Python 中的 ANSI 转义码?

问题描述 投票:0回答:3

为了检测控制台是否正确

sys.stderr
sys.stdout
,我做了以下测试:

if hasattr(sys.stderr, "isatty") and sys.stderr.isatty():
   if platform.system()=='Windows':
       # win code (ANSI not supported but there are alternatives)
   else:
       # use ANSI escapes
else:
   # no colors, usually this is when you redirect the output to a file

现在,通过 IDE(如 PyCharm)运行此 Python 代码时,问题变得更加复杂。最近 PyCharm 添加了对 ANSI 的支持,但第一次测试失败了:它具有

isatty
属性但设置为
False

我想修改逻辑,以便正确检测输出是否支持 ANSI 着色。一个要求是,在任何情况下,当输出被重定向到一个文件时,我都不应该输出一些东西(对于控制台来说,这是可以接受的)。

更新

https://gist.github.com/1316877

添加了更复杂的 ANSI 测试脚本
python console stdout ansi-escape windows-controls
3个回答
26
投票

Django 用户可以使用

django.core.management.color.supports_color
功能。

if supports_color():
    ...

他们使用的代码是:

def supports_color():
    """
    Returns True if the running system's terminal supports color, and False
    otherwise.
    """
    plat = sys.platform
    supported_platform = plat != 'Pocket PC' and (plat != 'win32' or
                                                  'ANSICON' in os.environ)
    # isatty is not always implemented, #6223.
    is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
    return supported_platform and is_a_tty

参见https://github.com/django/django/blob/master/django/core/management/color.py


12
投票

我可以告诉你其他人是如何解决这个问题的,但它并不漂亮。如果您以 ncurses 为例(它需要能够在各种不同的终端上运行),您会看到它们使用 terminal capabilities database 来存储各种终端及其功能。关键是,即使是他们也永远无法自动“检测”到这些东西。

我不知道是否有跨平台的 termcap,但它可能值得您花时间寻找它。即使它在那里,它也可能没有列出您的终端,您可能必须手动添加它。


0
投票

\x1B[6n
是标准的(据我所知)ANSI 转义代码,用于查询用户光标的位置。如果发送到 stdout,终端应将
\x1B[{line};{column}R
写入 stdin。如果达到此结果,则可以假设支持 ANSI 转义码。主要问题是检测这个回复。

视窗

msvcrt.getch
可用于从标准输入中检索字符,而无需等待按下回车键。这与
msvcrt.kbhit
相结合,它检测标准输入是否正在等待读取,从而产生在这篇文章的 Code w/ Comments 部分中找到的代码。

Unix/带有 termios

警告:我(不建议)没有测试这个特定的 tty/select/termios 代码,但知道过去可以使用类似的代码。

getch
kbhit
可以使用
tty.setraw
select.select
复制。因此我们可以定义这些函数如下:

from termios import TCSADRAIN, tcgetattr, tcsetattr
from select import select
from tty import setraw
from sys import stdin

def getch() -> bytes:
    fd = stdin.fileno()                        # get file descriptor of stdin
    old_settings = tcgetattr(fd)               # save settings (important!)

    try:                                       # setraw accomplishes a few things,
        setraw(fd)                             # such as disabling echo and wait.

        return stdin.read(1).encode()          # consistency with the Windows func
    finally:                                   # means output should be in bytes
        tcsetattr(fd, TCSADRAIN, old_settings) # finally, undo setraw (important!)

def kbhit() -> bool:                           # select.select checks if fds are
    return bool(select([stdin], [], [], 0)[0]) # ready for reading/writing/error

这可以与下面的代码一起使用。

带注释的代码

from sys import stdin, stdout

def isansitty() -> bool:
    """
    The response to \x1B[6n should be \x1B[{line};{column}R according to
    https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797. If this
    doesn't work, then it is unlikely ANSI escape codes are supported.
    """

    while kbhit():                         # clear stdin before sending escape in
        getch()                            # case user accidentally presses a key

    stdout.write("\x1B[6n")                # alt: print(end="\x1b[6n", flush=True)
    stdout.flush()                         # double-buffered stdout needs flush 

    stdin.flush()                          # flush stdin to make sure escape works
    if kbhit():                            # ANSI won't work if stdin is empty
        if ord(getch()) == 27 and kbhit(): # check that response starts with \x1B[
            if getch() == b"[":
                while kbhit():             # read stdin again, to remove the actual
                    getch()                # value returned by the escape

                return stdout.isatty()     # lastly, if stdout is a tty, ANSI works
                                           # so True should be returned. Otherwise,
    return False                           # return False

没有注释的完整代码

如果你想要它,这里是原始代码。

from sys import stdin, stdout
from platform import system


if system() == "Windows":
    from msvcrt import getch, kbhit

else:
    from termios import TCSADRAIN, tcgetattr, tcsetattr
    from select import select
    from tty import setraw
    from sys import stdin

    def getch() -> bytes:
        fd = stdin.fileno()
        old_settings = tcgetattr(fd)

        try:
            setraw(fd)

            return stdin.read(1).encode()
        finally:
            tcsetattr(fd, TCSADRAIN, old_settings)

    def kbhit() -> bool:
        return bool(select([stdin], [], [], 0)[0])

def isansitty() -> bool:
    """
    Checks if stdout supports ANSI escape codes and is a tty.
    """

    while kbhit():
        getch()

    stdout.write("\x1b[6n")
    stdout.flush()

    stdin.flush()
    if kbhit():
        if ord(getch()) == 27 and kbhit():
            if getch() == b"[":
                while kbhit():
                    getch()

                return stdout.isatty()

    return False

来源

排名不分先后:

© www.soinside.com 2019 - 2024. All rights reserved.