最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python读取和解析配置文件作为配置选项

Python crifan 3476浏览 0评论

折腾:

【记录】尝试用Python操作PhantomJS+Selenium去模拟购物操作

期间,希望实现,把代码中一些配置项,比如

输出文件夹叫做output等

作为可配置的项,放到配置文件中,然后用python去加载配置文件,读取配置

python config file

python config file best practices

Configuration files in Python · Martin Thoma

果然很我猜的类似:

就是用json文件,然后python可以用json库加载和解析出配置

parsing – What’s the best practice using a settings file in Python? – Stack Overflow

13.2. ConfigParser — Configuration file parser — Python 2.7.14 documentation

python中有专门的解析.cfg的ConfigParser

不过明显用起来很麻烦。

ConfigParserExamples – Python Wiki

支持ini的配置,但是也不够灵活。

Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school – Stack Overflow

【总结】

目前用:

<code># init and parse config
with open('config.json') as configJsonFile:
    # &lt;open file 'config.json', mode 'r' at 0x10e868390&gt;
    gCfg = json.load(configJsonFile)
    #{u'befrugal': {u'username': u'xxx', u'password': u'yyy'}, u'outputFolder': u'output'}
</code>

对应配置文件config.json内容:

<code>{
  "outputFolder" : "output",
  "befrugal" : {
    "username" : "xxx",
    "password" : "yyy"
  }
}
</code>

实现了基本的读取和解析配置文件,后续就可以得到dict的变量的配置变量去使用了:

<code># init output folder
if not os.path.exists(gCfg["outputFolder"]):
    os.makedirs(gCfg["outputFolder"])

# init logging
filenameNoSufx = crifanLib.getInputFileBasenameNoSuffix()
logFilename = os.path.join(gCfg["outputFolder"], filenameNoSufx + ".log")
crifanLib.loggingInit(logFilename)
# logging.info("filenameNoSufx=%s", filenameNoSufx)
logging.info("Current log filename: %s", logFilename)
logging.info("Current config: %s", gCfg)
</code>

转载请注明:在路上 » 【已解决】Python读取和解析配置文件作为配置选项

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.162 seconds, using 22.13MB memory