2016-03-01 57 views
1

美好的一天。我正在嘗試爲我的pythonanywhere代碼創建一個快速的&髒配置文件。我嘗試使用YAML,但結果很奇怪。Yaml在pythonanywhere的Python3版本中無法正常工作

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)的,而不是插入新行?爲什麼它包括「符號?

回答

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() 
+0

哇,我不能相信我錯過了。非常感謝你。 :) – hombrepython

相關問題