你可以如何在Python中使用外部配置文件的值来初始化变量类型的数组?

huangapple go评论67阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月12日 22:37:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定