繁体   English   中英

Python的ConfigParser使用

[英]Python use of ConfigParser

我在.txt文件中存储了一些属性,这些属性供存储在多个模块中的几种不同的类和函数使用。 为了能够从这些不同的位置访问属性,我有一个空白模块。

将模块本身设置为ConfigParser对象还是读取所有参数并将它们设置为模块级属性更好?

即第一路

blank_module = ConfigParser.ConfigParser()
blank_module.read("file.txt")

Then access with blank_module.get('section1', 'property1')

VS

local_var = ConfigParser.ConfigParser()
local_var.read("file.txt")

blank_module.property1 = local_var.get('section1', 'property1')
blank_module.property2 = local_var.get('section1', 'property2')
etc... 
then access with blank_module.property1

当访问参数时,第二种方法看起来更优雅,但是我不确定它们在性能方面会有何不同。

我认为这不是您应该担心的性能。 问题是易于使用。 这些模块的用户可能会发现,访问从文件中提取的变量比使用ConfigParser API更方便。

此外,您可以在模块中进行错误检查,以便解决读取文件时遇到的问题:

import ConfigParser
local_var = ConfigParser.ConfigParser()
try:
    local_var.read("file.txt")
except (ConfigParser.Error, OSError) as e:
    # Error reading 'file.txt' or something like that

try:
    blank_module.property1 = local_var.get('section1', 'property1')
except ConfigParser.Error as e:
    # Handle the error
try:
    blank_module.property2 = local_var.get('section1', 'property2')
except ConfigParser.Error as e:
    # Handle the error
etc... 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM