【问题标题】:Yaml not working properly in Python3 version of pythonanywhereYaml 在 Python3 版本的 pythonanywhere 中无法正常工作
【发布时间】:2016-03-01 16:42:56
【问题描述】:

美好的一天。我正在尝试为我的 pythonanywhere 代码创建一个快速而肮脏的配置文件。我尝试使用 YAML,但结果很奇怪。

import os

import yaml

yaml_str = """Time_config:
    Tiempo_entre_avisos: 1
    Tiempo_entre_backups: 7
    Tiempo_entre_pushes: 30
Other_config:
    Morosos_treshold: 800
Mail_config:
    Comunication_mail: ''
    Backup_mail: ''
    Director_mail: []
"""

try:
    yaml_file = open("/BBDD/file.yml", 'w+')
except:
    print("FILE NOT FOUND")
else:
    print("PROCESSING FILE")
    yaml.dump(yaml_str, yaml_file, default_flow_style=False)
    a = yaml.dump(yaml_str, default_flow_style=False)
    print(a) #I make a print to debug
    yaml_file.close()

代码似乎运行良好。但是,结果似乎已损坏。无论是在文件中还是在打印中,它看起来都是这样的(包括“s):

"Time_config:\n    Tiempo_entre_avisos: 1\n    Tiempo_entre_backups: 7\n    Tiempo_entre_pushes:\  \ 30\nOther_config:\n    Morosos_treshold: 800\nMail_config:\n    Comunication_mail:\  \ ''\n    Backup_mail: ''\n    Director_mail: []\n"

如果我在 python 控制台中复制并粘贴该字符串,yaml 会给我预期的结果,就是这个:

Time_config:
    Tiempo_entre_avisos: 1
    Tiempo_entre_backups: 7
    Tiempo_entre_pushes: 30
Other_config:
    Morosos_treshold: 800
Mail_config:
    Comunication_mail: ''
    Backup_mail: ''
    Director_mail: []

为什么会这样?为什么我在第一枪中没有得到结果?为什么要打印换行符 (\n) 而不是插入新行?为什么它包含 " 符号?

【问题讨论】:

    标签: python python-3.x yaml pythonanywhere


    【解决方案1】:

    我认为你应该先从字符串中加载 yaml,然后继续:

    # Everything before here is the same
        print("PROCESSING FILE")
        yaml_data = yaml.load(yaml_str)
        yaml.dump(yaml_data, yaml_file, default_flow_style=False)
        a = yaml.dump(yaml_data, default_flow_style=False)
        print(a) #I make a print to debug
        yaml_file.close()
    

    【讨论】:

    • 哇,我不敢相信我错过了。非常感谢你。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 2014-07-11
    • 2022-09-28
    • 2015-04-05
    • 1970-01-01
    相关资源
    最近更新 更多