Python:读入来自 JSON 的颜色代码

Python: Read in Colors Codes from JSON

我有兴趣创建一个项目,其中 python 脚本将创建彩色输出。我的项目结构是这样的,我想创建一个包含颜色代码 (ANSI) 的 settings.json 文件(由用户处理)。

这是我的 settings.json 文件的样子。请注意,在 bash 配置文件中,您通常会使用一个转义字符来指示颜色代码,但 Python 不允许我读取只有一个转义字符的文件。 :

{
  "column_head_color": {
    "group1": "\033[91m",
    "group2": null
  }
}

这是主要模块:

import json


# import settings
with open('settings.json', encoding='utf-8') as file:
    settings = json.load(file)


for column in settings['column_head_color']:
    color_setting = settings['column_head_color'][column]

    if color_setting is None:
    # if setting is null, reset color
        settings['column_head_color'][column] = "3[0m"   # reset; if I change the string to "\033[94m", output shows actual color

    else:
        # if there is a color code present, should I replace "\" with "\"?
        settings['column_head_color'][column] = settings['column_head_color'][column].replace("\\", "\")



print("{}This is the group1".format(settings['column_head_color']['group1']))       # output shows the color code, but it does not actually format the text
print("{}This is the group2".format(settings['column_head_color']['group2']))       # output here works, because it was hard coded manually

我试过用一个转义字符替换两个转义字符,我也试过使用 repr() 函数,但无济于事。我只展示了如下所示的输出:

>>> python main.py
3[91mOutput

对于group2,颜色代码有效,因为我在脚本中手动输入了代码。但是,当我从 JSON 文件中以 group1 的类似字符串读取它时,Python 不会以相同的方式解释它。如何提示我的 python 程序将该字符串解释为颜色代码?

您可以按照以下步骤使其工作:

  1. 像这样格式化您的 json 文件:

    {
        "Black" : "30",
        "Red" : "31",
        "Green" : "32",
        "Yellow" : "33",
        "Blue" : "34",
        "Magenta" : "35",
        "Cyan" : "36",
        "White" : "37"
    }
    
  2. 查找并加载 JSON 文件

    // Replace PATH_TO__FILE and FILE_NAME accordingly  
    const colors = require('PATH_TO_FILE/FILE_NAME.json')
    
  3. 创建一个以不同颜色输出的函数。例如:

    function consoleLogColor(color, text) {
        console.log(`\x1b[${colors[color]}m%s\x1b[0m`, text);
    }
    consoleLogColor('Blue', 'HI');