前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3 读取 toml 配置文件

Python3 读取 toml 配置文件

作者头像
py3study
发布2020-01-03 11:17:26
3K0
发布2020-01-03 11:17:26
举报
文章被收录于专栏:python3python3

【吐槽】

    先吐槽一下其他几个配置文件。

  • 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】

代码语言:javascript
复制
# 输入目录
SrcRoot = 'D:\test\input'

# 输出目录
DstRoot = 'D:\test\output'

【t.py】

代码语言:javascript
复制
#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】

代码语言:javascript
复制
D:\Python3Project\test>python3 t.py
SrcRoot: D:\test\input
DstRoot: D:\test\output
Read config.toml successed!
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档