[英]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.