Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何检测控制台是否支持Python中的ANSI转义码?_Python_Console_Stdout_Ansi Escape_Windows Controls - Fatal编程技术网

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

如何检测控制台是否支持Python中的ANSI转义码?,python,console,stdout,ansi-escape,windows-controls,Python,Console,Stdout,Ansi Escape,Windows Controls,为了检测控制台是否正确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: #

为了检测控制台是否正确
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着色。一个要求是,在任何情况下,当输出被重定向到文件时,我都不应该输出某些内容(对于控制台来说,这是可以接受的)

更新

中添加了更复杂的ANSI测试脚本,我可以告诉您其他人是如何解决这个问题的,但它并不漂亮。如果您以ncurses为例(它需要能够在各种不同的终端上运行),您将看到它们使用a来存储各种终端及其功能。关键是,即使是他们也无法自动“检测”这些东西


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

Django用户可以使用
Django.core.management.color.supports\u 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

请参见

PyCharm团队报告,目前无法发现您的代码是在PyCharm内部执行的。解决方法是自己添加一个环境变量,但几乎没有用。这张PyCharm票据讨论了这个问题——(它引用了这个讨论,我认为也有一些相同的参与者)。它记录了他们添加了可用于检测PYCHARM的
PYCHARM\u HOSTED=1
环境变量。