首页 > 解决方案 > 配置解析器从ini文件中获取“单词列表”后如何将它们转换为变量

问题描述

我有一个脚本,它使用配置解析器来获取一个使用配置解析器的列表和一个使用它的 ini 文件,因为最终用户将放入他或她自己的列表以在排序脚本中使用

config.ini 文件的一部分示例

[ConfigFile]
#L1 Category to Keep
l1cat=('Audio Terminal', 'Communications/Telephone', 'Microphones', 'Speakers', 'Tour Sound')

我的脚本中有这个来获取ini文件

import configparser
from configparser import ConfigParser
config = ConfigParser()
config.read("SortingConfig.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

我遇到的问题部分....正在转动

l1cat=('Audio Terminal', 'Communications/Telephone', 'Microphones', 'Speakers', 'Tour Sound')

变成一个可用的变量值

在我的脚本中,我有这个

xls_book = xlrd.open_workbook(infilepath, formatting_info = True, encoding_override = "cp1252", logfile = open(os.devnull, 'w'))
sheetname = xls_book.sheet_by_index(0).name

df = pd.read_excel(xls_book, engine = 'xlrd',parse_dates = ['Date'])
df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%y %H:%M:%S').dt.strftime('%m/%d/%y %H:%M')

## L1 Category keep if isin list
df = df.loc[df['L1 Category'].isin(l1cat)]

我得到的错误是 TypeError: only list-like objects are allowed to be pass to isin(), you pass a [str]

在最终用户需要对其进行动态更改之前,我可以将 l1cat = ('stuff','more stuff','even more stuff') 添加为常规变量,并且效果很好

我使用配置解析器的原因是因为当我编译为 EXE 时,我需要一些可以随时通过配置文件更改变量的东西

我实际上需要它来工作就像我l1cat = ('stuff','more stuff','even more stuff')直接在我的脚本中输入了一样


固定文件看起来像这样仍然使用与上面相同的 ini 示例

import configparser
from configparser import ConfigParser
from ast import literal_eval
config = ConfigParser()
config.read("SortingConfig.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

#The Variable gets Defined
l1catV = literal_eval(config['ConfigFile']['l1cat'])

###Further down in my script as I need to use the variable
xls_book = xlrd.open_workbook(infilepath, formatting_info = True, encoding_override = "cp1252", logfile = open(os.devnull, 'w'))
sheetname = xls_book.sheet_by_index(0).name

df = pd.read_excel(xls_book, engine = 'xlrd',parse_dates = ['Date'])
df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%y %H:%M:%S').dt.strftime('%m/%d/%y %H:%M')

## L1 Category keep if isin list

##Variable gets used
df = df.loc[df['L1 Category'].isin(l1catV)]

标签: pythonconfigparser

解决方案


您可以使用ast.literal_eval( doc ) 解析值:

txt = '''
[ConfigFile]
#L1 Category to Keep
l1cat=('Audio Terminal', 'Communications/Telephone', 'Microphones', 'Speakers', 'Tour Sound')
'''

import configparser
from configparser import ConfigParser
from ast import literal_eval

config = ConfigParser()
#####config.read_string(txt)###### - This portion was incorrect



my_tuple = literal_eval(config['ConfigFile']['l1cat'])

for val in my_tuple:
    print(val)

印刷:

Audio Terminal
Communications/Telephone
Microphones
Speakers
Tour Sound

推荐阅读