YAML 在Python中的應用

 

    編程免不了要寫配置文件,怎麼寫配置也是一門學問。html

    YAML 是專門用來寫配置文件的語言,很是簡潔和強大,遠比 JSON 格式方便。python

    YAML在python語言中有PyYAML安裝包,下載地址:https://pypi.python.org/pypi/PyYAMLmysql

  1、簡介

    YAML 語言(發音 /ˈjæməl/ )的設計目標,就是方便人類讀寫。它實質上是一種通用的數據串行化格式。web

    它的基本語法規則以下:sql

    一、大小寫敏感編程

    二、使用縮進表示層級關係json

    三、縮進時不容許使用Tab鍵,只容許使用空格。數組

    四、縮進的空格數目不重要,只要相同層級的元素左側對齊便可ruby

    五、# 表示註釋,從這個字符一直到行尾,都會被解析器忽略,這個和python的註釋同樣數據結構

 

    YAML 支持的數據結構有三種:

    一、對象:鍵值對的集合,又稱爲映射(mapping)/ 哈希(hashes) / 字典(dictionary)

    二、數組:一組按次序排列的值,又稱爲序列(sequence) / 列表(list)

    三、純量(scalars):單個的、不可再分的值。字符串、布爾值、整數、浮點數、Null、時間、日期

 

  2、字符串

    

#######################################字符串##############################################
#一、字符串默認不使用引號表示
str1: 這是一個字符串

#二、若是字符串之中包含空格或特殊字符,須要放在引號之中。
str2: '內容: *字符串'

#三、單引號和雙引號均可以使用,雙引號不會對特殊字符轉義。
str3: '內容\n字符串'
str4: "content\n string"

#四、單引號之中若是還有單引號,必須連續使用兩個單引號轉義。
s3: 'labor''s day'

#五、字符串能夠寫成多行,從第二行開始,必須有一個單空格縮進。換行符會被轉爲空格
strline: 這是一段
  多行
  字符串
  
#六、多行字符串可使用|保留換行符,也可使用>摺疊換行
this: |
  Foo
  Bar
that: >
  Foo
  Bar
  
#七、+表示保留文字塊末尾的換行,-表示刪除字符串末尾的換行。
s4: |
  Foo4
s5: |+
  Foo5
s6: |-
  Foo6
s7: |
  Foo7

  

  3、對象

###################################對象####################
#一、對象的一組鍵值對,使用冒號結構表示。
animal: pets  #{'animal': 'pets'}
#
##二、Yaml 也容許另外一種寫法,將全部鍵值對寫成一個行內對象
dict1: { name: Steve, foo: bar } #{'dict1': {'foo': 'bar', 'name': 'Steve'}}

 

 

  4、數組

####################################數組###################

# 一、數組能夠採用行內表示法。
animal: [Cat, Dog]

#{'animal': ['Cat', 'Dog']}

#二、一組連詞線開頭的行,構成一個數組。
animal1:
 - Cat
 - Dog
 - Goldfish

# {'animal1': ['Cat', 'Dog', 'Goldfish']}

 

 

  5、複合結構

############################複合結構##########################
#對象和數組能夠結合使用,造成複合結構

languages:
 - Ruby
 - Perl
 - Python
websites:
 YAML: yaml.org
 Ruby: ruby-lang.org
 Python: python.org
 Perl: use.perl.org
#{'languages': ['Ruby', 'Perl', 'Python'], 'websites': {'Python': 'python.org', 'YAML': 'yaml.org', 'Ruby': 'ruby-lang.org', 'Perl': 'use.perl.org'}}

db:
    host: xxx
    port: 3306
    user: weibospider
    password: xxx
    db_name: weibo
    db_type: mysql

#{'db': {'host': 'xxx', 'db_name': 'weibo', 'user': 'weibospider', 'db_type': 'mysql', 'password': 'xxx', 'port': 3306}}

 

  6、純量

##########################純量#############################
#一、數值直接以字面量的形式表示
number: 12.30 #{'number': 12.3}

#二、布爾值用true和false表示
isSet: true #{'isSet': True}
isSet1: false #{'isSet1': False}

三、null用~表示
parent: ~   #{'parent': None}

#四、時間採用 ISO8601 格式。
time1: 2001-12-14t21:59:43.10-05:00  #{'time1': datetime.datetime(2001, 12, 15, 2, 59, 43, 100000)}

##五、日期採用複合 iso8601 格式的年、月、日表示。
date: 2017-07-31  #{'date': datetime.date(2017, 7, 31)}

#六、YAML 容許使用兩個感嘆號,強制轉換數據類型。
int_to_str: !!str 123  #{'bool_to_str': 'true'}
bool_to_str: !!str true #{'bool_to_str': 'true'}

 

  7、YAML應用

    這裏主要是記錄一下YAML在Python語言中的應用。類比於json庫,yaml庫與其有驚人的類似之處。一個load方法,一個dump方法。顧名知義,也比較的好理解。

 

# coding:utf-8
import os

import sys
reload(sys)
sys.setdefaultencoding('utf8')

from yaml import load
config_path = os.path.join(os.path.dirname(__file__), 'tt.yaml')


with open(config_path,'rb') as f:
    cont = f.read()

cf = load(cont)

print cf.get('db')
# 輸出:{'host': 'xxx', 'db_name': 'weibo', 'user': 'weibospider', 'db_type': 'mysql', 'password': 'xxx', 'port': 3306}
print '------------------'

print cf

# 輸出:
'''
{'
    dict1': {'foo': 'bar', 'name': 'Steve'},
    'animal1': ['Cat', 'Dog', 'Goldfish'],
    'parent': None,
    'bool_to_str': 'true',
    'db': {'host': 'xxx', 'db_name': 'weibo', 'user': 'weibospider', 'db_type': 'mysql', 'password': 'xxx', 'port': 3306},
    'number': 12.3,
    'websites': {'Python': 'python.org', 'YAML': 'yaml.org', 'Ruby': 'ruby-lang.org', 'Perl': 'use.perl.org'}, 
    'time1': datetime.datetime(2001, 12, 15, 2, 59, 43, 100000), 
    'languages': ['Ruby', 'Perl', 'Python'],
    'animal': ['Cat', 'Dog'],
    'date': datetime.date(2017, 7, 31),
    'int_to_str': '123', 
    'isSet': True, 
    'isSet1': False}
'''

 

 

  參考文檔:http://www.ruanyifeng.com/blog/2016/07/yaml.html

相關文章
相關標籤/搜索