英文:
How can I initialise a variable type array in python with values from an externa config file?
问题
我有一个包含一些配置的文件
[ERU]
refreschtime = 15
forwardToA = test@gmail.com
forwardToB = test1@gmail.com, test2@gmail.com
现在我想将forwardToB
用作数组,而不是单个字符串,以便与数组成员交互
for recipient in recipients:
log.info(recipient)
to_recipients.append(Mailbox(email_address=recipient))
对于单个收件人,脚本工作正常。但是,当尝试插入一组收件人时,它会失败,因为它将整个列表视为单个项目。
这是如何将配置导入脚本的方式
try:
forwardToB = [config.get('ERU', 'forwardToB')]
except configparser.NoOptionError:
log.critical('configuration文件中未指定forwardToB')
英文:
I got a file with some configuration
[ERU]
refreschtime = 15
forwardToA = test@gmail.com
forwardToB = test1@gmail.com, test2@gmail.com
Now I wanted to use forwardToB as an array instead of single string to interact over the array members
for recipient in recipients:
log.info(recipient)
to_recipients.append(Mailbox(email_address=recipient))
The script is working fine for a single recipient. However when try to insert a list of recipients it fail as it take the whole list as single item.
The is how I'm imported the config into the script
try:
forwardToB = [config.get('ERU', 'forwardToB')]
except configparser.NoOptionError:
log.critical('no forwardToB specified in configuration file')
答案1
得分: 2
你可以尝试:
forwardToB = [elem.strip() for elem in config.get('ERU', 'forwardToB').split(',')]
split(',')
将字符串拆分成一个包含原始字符串中由逗号分隔的子字符串的数组(逗号不包括在内)strip
用于删除元素周围的空格。
英文:
You can try:
forwardToB = [elem.strip() for elem in config.get('ERU', 'forwardToB').split(',')]
split(',')
split a string to an array containing substring separated by a comma in the original string (the comma is not included)strip
is to remove whitespace around your elements
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论