Python3 讀取 toml 配置檔案(UTF-8/UTF-8-BOM)
阿新 • • 發佈:2018-12-10
【吐槽】
先吐槽一下其他幾個配置檔案。
ini:表達能力不夠,比如不能表達列表等結構;沒有官方註釋符號,雖然一般以分號作為註釋符號。
json:沒有官方註釋符號,雖然某些第三方包提供了註釋結構。
yaml:語法比較複雜,可讀性不太高。
【toml 簡介】
TOML是前GitHub CEO, Tom Preston-Werner,於2013年建立的語言,其目標是成為一個小規模的易於使用的語義化配置檔案格式。TOML被設計為可以無二義性的轉換為一個雜湊表(Hash table)。
官方中文介紹在這裡: https://github.com/toml-lang/toml/tree/master/versions/cn
walker 下面使用的第三方解析包是:https://pypi.org/project/toml/
【config.toml】
# 輸入目錄 SrcRoot = 'D:\test\input' # 輸出目錄 DstRoot = 'D:\test\output'
【t.py】
#encoding=utf-8 #author: walker #date: 2018-12-11 #summary: 讀取 UTF-8/UTF-8-BOM 格式的 toml 配置檔案 import os import sys import toml SrcRoot = r'' DstRoot = r'' #讀取配置檔案 def ReadConfig(): global SrcRoot, DstRoot cfgFile = 'config.toml' if not os.path.exists(cfgFile): input(cfgFile + ' not found') sys.exit(-1) with open(cfgFile, mode='rb') as f: content = f.read() if content.startswith(b'\xef\xbb\xbf'): # 去掉 utf8 bom 頭 content = content[3:] dic = toml.loads(content.decode('utf8')) SrcRoot = dic['SrcRoot'].strip() if not os.path.exists(SrcRoot): print('Error: not exists %s' % SrcRoot) sys.exit(-1) print('SrcRoot: %s' % SrcRoot) DstRoot = dic['DstRoot'].strip() if not os.path.exists(DstRoot): print('Error: not exists %s' % DstRoot) sys.exit(-1) print('DstRoot: %s' % DstRoot) print('Read config.toml successed!') if __name__ == '__main__': ReadConfig()
【cmd】
D:\Python3Project\test>python3 t.py SrcRoot: D:\test\input DstRoot: D:\test\output Read config.toml successed!
【相關閱讀】
*** walker ***