python读取配置文件,yaml模块读取yml文件

ymal文件编写语法参考http://www.ruanyifeng.com/blog/2016/07/yaml.html

ymal在python中的安装:pip install pyyaml

yml文件示例代码如下,此处命名为Data_data.yml:

email:
  user: 111111@qq.com
  pwd: 11111111
  smtpserver: smtp.qq.com
  foms: ["23123213123@163.com","5534534@qq.com"]
  url: http://234.345.327.534:8080/
  timeout: 10
  shulie:
    - 1
    - 2
    - 3
    - 4
    - 5
    - 6
    - 7
    - 8
    - 9
    - 10

读取yml文件示例代码:

import yaml,os

path1 = os.path.dirname(__file__) #获取当前文件的上级目录路径
path2=os.path.dirname(path1)
path3=os.path.dirname(path2)
path3=str(path3)
class yaml_read():
    def __init__(self):
        with open(path3+"/ever_day_mode/ymal模块练习/Data_data.yml",'r',encoding='utf-8') as fp:
            cc=fp.read()
        # self.xx=yaml.load(self.cc)#单独使用这种会报警告   可使用yaml.warnings({'YAMLLoadWarning': False})全局禁用警告
        self.r=yaml.unsafe_load(cc)#不安全的加载YAML语言的子集
        self.x=yaml.load(cc,Loader=yaml.FullLoader)#FullLoader:加载完整的YAML语言。避免执行任意代码。当前是yaml.load(input)(在发出警告之后)调用的默认加载程序。
        self.s=yaml.safe_load(cc)#安全地加载YAML语言的子集。建议加载不可信的输入
    def get_user(self):
        return self.r['email']['user']

if __name__ == '__main__':
    y=yaml_read()
    print(y.r['email'])
    x=y.get_user()
    print(x)
    print(y.x['email'])
    print(y.s["email"]['pwd'])
    print(y.s['email']['shulie'])
    # print(os.getcwd())
    # print(path3)

运行结果:

 跨文件调用示例:

from ymal模块练习.ymal_demo01 import *


y=yaml_read()
print(y.r['email'])

示例结果:

 

posted @ 2020-10-21 15:24  菌子石雨  阅读(604)  评论(0编辑  收藏  举报