【问题标题】:config parser not returning correct variable - leaves out ( ) around words配置解析器没有返回正确的变量 - 在单词周围省略 ( )
【发布时间】:2019-06-08 05:19:16
【问题描述】:

我有一个脚本,它在 excel 文件中获取一些数据并对其进行排序,并为一些关键内容添加一些颜色...... 我使用的是外部 .ini 文件,因为它有时需要根据用户当天的需求进行更改

ini文件基本上是这样的

[section]
#Color 1
color01 = ('00FCC84E')
cat1 = ('Item1','Item2')

#Color 2
color02 = ('00F4426E')
cat2 = ('Thingy Size 5/16')

使用配置解析器的我的脚本部分执行此操作

import configparser
from configparser import ConfigParser
from ast import literal_eval
config = ConfigParser()
config.read("MyFile.ini")
config.sections()

def variables(section):
    dict1 = {}
    options = config.options(section)
    for option in options:
        try:
            dict1[option] = config.get(section, option)
            if dict1[option] == -1:
                DebugPrint("skip: %s" % option)
        except:
            print("exception on %s!" % option)
            dict1[option] = None
    return dict1


color01V = literal_eval(config['ConfigFile']['color01'])
color02V = literal_eval(config['ConfigFile']['color02'])

cat01V = literal_eval(config['ConfigFile']['cat1'])
cat02V = literal_eval(config['ConfigFile']['cat2'])

print(cat01V)
print(cat02V)

返回

('Item1','Item2')
Thingy Size 5/16

为什么返回的第二个字符串没有 () 以及如何修复它。

我实际上需要在以后使用变量时出现 ()

【问题讨论】:

  • 这是因为您使用的 literal_eval() 需要/需要 Python 语法。您在 .ini 文件中使用了cat2 = ('Thingy Size 5/16',),表达式将计算为一个项目的tuple('Thingy Size 5/16',)

标签: python configparser


【解决方案1】:

您是否尝试过将“cat1”的值放在引号中?

[section]
color01 = ('00FCC84E')
cat1 = "('Item1','Item2')"
...
cat2 = "('Thingy Size 5/16')"

【讨论】:

  • 它似乎无法正常工作,因为即使我在它周围加上“,它也会为第二种颜色着色包含“Thingy Size 5/16”的项目
  • 所以我昨晚尝试了一些测试作为测试,它似乎是配置解析器处理单个参数与多个参数的问题。
  • 如果我使用 2 个或更多项目,它完全可以找到...但是单个项目和脚本不起作用
  • 所以如果我使用"Item1" , "Item2",它会返回('Item1' , 'Item2'),如果我使用"Item1Only",它会返回Item1Only
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 1970-01-01
  • 2015-02-25
相关资源
最近更新 更多