【问题标题】:Reading YAML file with Python results in AttributeError使用 Python 读取 YAML 文件会导致 AttributeError
【发布时间】:2017-06-17 21:30:11
【问题描述】:

我正在尝试编写一个脚本来备份 MySQL 数据库。我有一个config.yml 文件:

DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'

现在我需要阅读这个文件。到目前为止我的 Python 代码:

import yaml
config = yaml.load(open('config.yml'))
print(config.DB_NAME)

这是一个错误:

file "conf.py", line 4, in <module>
print(config.DB_NAME)
AttributeError: 'str' object has no attribute 'DB_NAME'

有人知道我在哪里犯了错误吗?

【问题讨论】:

  • 欢迎来到 SO btw。问题可能很简单,格式很好,所有有用的元素都在这里。享受您的住宿,当您的问题得到完全回答时,不要忘记将答案标记为已批准:)
  • 您不应该使用yaml.load(),因为它可能不安全,而且从您的问题来看,您似乎没有经验来正确判断您是否受到影响(请改用.safeload() )。如果读取config.yml 引发错误(解析时),您的代码也会出现问题,在这种情况下,您的文件可能无法正确关闭。您应该使用with 声明

标签: python yaml


【解决方案1】:

有两个问题:

  • 正如其他人所说,yaml.load() 将关联数组加载为映射,因此您需要使用config['DB_NAME']
  • 您的配置文件中的语法不正确:在 YAML 中,键与值之间用冒号+空格分隔。

如果文件格式如下:

DB_HOST: 'localhost'
DB_USER: 'root'
DB_USER_PASSWORD: 'P@$$w0rd'
DB_NAME: 'moodle_data'
BACKUP_PATH: '/var/lib/mysql/moodle_data'

【讨论】:

    【解决方案2】:

    要备份您的数据库,您应该能够将其导出为.sql 文件。如果您使用的是特定接口,请查找Export

    然后,对于 Python 的 yaml 解析器。

    DB_HOST :'localhost'
    DB_USER : 'root'
    DB_USER_PASSWORD:'P@$$w0rd'
    DB_NAME : 'moodle_data'
    BACKUP_PATH : '/var/lib/mysql/moodle_data'
    

    key-value 的东西(抱歉,没有找到更好的词来形容那个)。在某些语言中(例如我认为的 PHP),它们被转换为 objects。但是在 python 中,它们被转换为 dicts(yaml 解析器可以做到这一点,JSON 解析器也可以)。

    # access an object's attribute
    my_obj.attribute = 'something cool'
    my_obj.attribute # something cool
    del my_obj.attribute
    my_obj.attribute # error
    
    # access a dict's key's value
    my_dict = {}
    my_dict['hello'] = 'world!'
    my_dict['hello'] # world!
    del my_dict['hello']
    my_dict['hello'] # error
    

    所以,这是一个非常快速的 dicts 演示文稿,但如果你让你继续前进(运行help(dict),和/或看看here,你不会后悔的)

    在你的情况下:

    config['DB_NAME'] # moodle_data
    

    【讨论】:

    • “JSON 编译器”实际上没有意义,因为解析 JSON 文档会生成数据结构,而不是程序。我想您的意思是 JSON 解析器,更具体地说,是 python 的默认 json 解析器。好点坚持使用the correct tool 进行数据库备份顺便说一句。
    • 哎呀...谢谢,已修复!
    • import yaml config=yaml.load(open('config.yml')) db=config['DB_NAME'] print db仍然出现TypeError“字符串索引必须是整数,而不是str”
    【解决方案3】:

    试试这个:

    import yaml
    with open('config.yaml', 'r') as f:
        doc = yaml.load(f)
    

    要访问“DB_NAME”,您可以使用:

    txt = doc["DB_NAME"]
    print txt
    

    【讨论】:

    • 它说 TypeError: string indices must be integers, not str
    • 最有可能是:doc[0]['DB_NAME'],原因。
    猜你喜欢
    • 2019-02-24
    • 2012-12-30
    • 2021-05-20
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多