Python3 讀取 toml 配置文件(UTF-8/UTF-8-BOM)

吐槽

    先吐槽一下其他幾個配置文件。

  • ini:表達能力不夠,比如不能表達列表等結構;沒有官方註釋符號,雖然一般以分號作爲註釋符號。
  • json:沒有官方註釋符號,雖然某些第三方包提供了註釋結構。
  • yaml:語法比較複雜,可讀性不太高。

toml 簡介

TOML是前GitHub CEO, Tom Preston-Werner,於2013年創建的語言,其目標是成爲一個小規模的易於使用的語義化配置文件格式。TOML被設計爲可以無二義性的轉換爲一個哈希表(Hash table)。

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():
    r""" 讀取配置文件 """
    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 snapshot
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章