python讀取配置檔案yaml
YAML:一種非標記語言,可以簡單表達清單、列表等資料形態,檔案字尾為 .yml
基本語法:
1.大小寫敏感
2.使用縮排表示層級關係
3.縮排不允許使用tab,只允許空格,但是對空格數不要求
4.# 表示註釋
資料型別
1.鍵值對
key: value ":"和value之間應該有空格
# 字典 {'name': "test", 'age': 12} name: test age: 12
2.列表
# 列表 [1,2 ,3] -1 -2 -3
3.複合結構
# 字典巢狀字典{'stud1': {'name': "test", 'age': 12}, 'stud2': {'name': "test2", 'age': 12}}stud1: name: test age: 12 stud2: name: test2 age:12 # 字典巢狀列表 {list1: [1,2,3], list2:[4,5,6]} list1: -1 -2 -3 list2: -4 -5 -6 # 列表巢狀列表,[[1,2,3], [4,5,6]] - -1 -2 -3 - -4 -5 -6
4.其他
a.引號
字元可以用單引號或者雙引號或者不用,單引號會將字元內的特殊符號轉義。eg. 'test\ntest',輸出是test\ntest
雙引號不會轉義特殊符號
b.文字塊 使用|標註的文字內容縮排表示的塊,可以保留塊中已有的換行符【存疑】
name: |
test
test
輸出果,會保留換行
name: | +
test
test
刪除文字塊末尾的換行
name: -
test
test
>將文字塊中的回車替換成空格
name: >
test
test
輸出test test
c.引用
&表示複製資料的別名以及內容,*表示引用
name: &a test
age: *a
輸出age=test
d.存量
布林值: true、false或者TRUE或者True
數字:
12 整數
0b1010_0111 二進位制
.inf 空值,無窮大
浮點數
1.2
1.2e+4 科學計數法
f.空值
null或者~表示
g.日期和時間
date:
- 2018-02-17 #日期必須使用ISO 8601格式,即yyyy-MM-dd
datetime:
- 2018-02-17T15:02:31+08:00 #時間使用ISO 8601格式,時間和日期之間使用T連線,最後使用+代表時區
h.強制型別轉換
單個感嘆號表示強制轉換資料型別,通常是自定義型別,雙歎號是內建型別轉換。
age: !!str
12
pyyaml
官網下載pyyaml安裝,或者使用pip安裝。
1.寫檔案
dict1 = {"oppo_findx2pro": {'platformName': "Android", 'platFormVersion': "10", 'deviceName': "dd", 'udid': "648d4f29", 'automationName': "UiAutomator2", 'noReset': False, 'unicodeKeyboard': True, 'resetKeyboard': True, 'appPackage': "com.tencent.mm", 'appActivity': "com.tencent.mm.ui.LauncherUI", 'autoGrantPermissions': True, 'chromedriverExecutable': r"C:\Users\v_yddchen\Desktop\chromedriver_win32 77.0\chromedriver.exe", 'chromeOptions': {'androidProcess': "com.tencent.mm:toolsmp"}} }
with open('test_dict.yaml', 'w', encoding='utf-8') as f: yaml.dump(dict1, f)
def dump(data, stream=None, Dumper=Dumper, **kwds): """ Serialize a Python object into a YAML stream. If stream is None, return the produced string instead. """ return dump_all([data], stream, Dumper=Dumper, **kwds)
2.讀檔案
def load(stream, Loader=None): """ Parse the first YAML document in a stream and produce the corresponding Python object. """ if Loader is None: load_warning('load') Loader = FullLoader loader = Loader(stream) try: return loader.get_single_data() finally: loader.dispose()
程式碼實現
def read_dict_yaml(): with open('test_dict.yaml', 'r', encoding='utf-8') as f: print(yaml.load(f.read()))
錯誤和警告
yaml.load()如果引數Loader使用預設值的話會報錯:YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.
官網解釋:https://msg.pyyaml.org/load
pyyaml提供了safe_load函式,該函式可以載入yam的子集。
或者使用Loader宣告載入器。
BaseLoader 基本載入器,載入最基本的YAML
SafeLoader 安全地載入YAML語言的子集,建議載入不信任的輸入
FullLoader 載入完整的YAML語言,避免執行任意程式碼(這是當前pyyaml 5.1在發出警告後呼叫的預設載入程式)
UnsafeLoder 也成為向後相容的Loader【存疑】