读取Python的Yaml配置文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读取Python的Yaml配置文件相关的知识,希望对你有一定的参考价值。
我正在尝试读取YAML配置文件并将其显示给终端。现在,我想尝试诸如检查YAML文件中的数据库(db)不是Sqlite还是Postgres的操作,然后会引发异常,但我不知道如何。我尝试了但失败了,我在做什么错?
我的test.yaml
文件:
db: mysql
dbopt:
host: zppp8alnTQc6jpfb.cds6ifjzc2el.ap-northeast-1.rds.amazonaws.com
port: 5432
dbname: meister_4ef1ef_mfgdata
user: analyzer
password: 9mtfkzvCqtaarlT2
client_encoding: utf-8
connect_timeout: 60
sslmode: none
query: select * from manufacturing_product
我的代码:
# process_yaml.py file`
import yaml
with open(r'D:Python est.yaml') as file:
# The FullLoader parameter handles the conversion from YAML
# scalar values to Python the dictionary format
data = yaml.full_load(file)
for item, doc in data.items():
print(item, ":", doc)
def __init__(self, dbconf):
self._dbconf = dict(dbconf)
# checking for database type
dbtype = self.get_db_type()
if dbtype != 'sqlite' and dbtype != 'postgres':
raise exceptions.InvalidConfigError(
'E01001', 'Invalid database type, should be sqlite or postgres.')
else:
self.dbtype = dbtype
我的程序仍然无法捕获异常。我的终端机:
db : mysql
dbopt : {'host': 'zppp8alnTQc6jpfb.cds6ifjzc2el.ap-northeast-1.rds.amazonaws.com', 'port': 5432, 'dbname': 'meister_4ef1ef_mfgdata', 'user': 'analyzer', 'password': '9mtfkzvCqtaarlT2', 'client_encoding':
'utf-8', 'connect_timeout': 60, 'sslmode': 'none'}
query : select * from manufacturing_product
答案
您的代码中缺少几段,并且永远不会调用函数__init__
。您可能从带有类的示例中复制了该示例,该类也具有方法get_db_type()
。
class InvalidConfigError(Exception):
pass
class DB:
def __init__(self, dbconf):
self._dbconf = dict(dbconf)
# checking for database type
dbtype = self.get_db_type()
if dbtype != 'sqlite' and dbtype != 'postgres':
raise InvalidConfigError(
'E01001', 'Invalid database type, should be sqlite or postgres.')
else:
self.dbtype = dbtype
def get_db_type(self):
return self._dbconf['db']
with open('test.yaml') as file:
data = yaml.full_load(file)
for item, doc in data.items():
print(item, ":", doc)
db = DB(data)
哪些印刷品:
db : mysql
dbopt : {'host': 'zppp8alnTQc6jpfb.cds6ifjzc2el.ap-northeast-1.rds.amazonaws.com', 'port': 5432, 'dbname': 'meister_4ef1ef_mfgdata', 'user': 'analyzer', 'password': '9mtfkzvCqtaarlT2', 'client_encoding': 'utf-8', 'connect_timeout': 60, 'sslmode': 'none'}
query : select * from manufacturing_product
然后给出:
init引发InvalidConfigError(main。InvalidConfigError :(“ E01001”,“无效的数据库类型,应为sqlite或postgres。”)进程错误命令'['ryd','--force','so-60160957.ryd']'返回非零退出状态1。
以上是关于读取Python的Yaml配置文件的主要内容,如果未能解决你的问题,请参考以下文章