我有一个脚本,它使用配置解析器和一个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:仅允许将类似列表的对象传递给isin(),您传递了[str]
在最终用户需要对其进行动态更改之前,我可以将l1cat=('stuff'、'more stuff'、'ever 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)]
我似乎有它的工作。。。除了部分解析返回了错误的变量,我不确定我遗漏了什么
在my config.ini中
当我使用
一个带()返回,另一个不带。。。。 我需要做什么才能让这两个都返回()
您可以使用
ast.literal_eval
(doc)来解析值:印刷品:
相关问题 更多 >
编程相关推荐