python配置文件
1、经试验以“.yml”结尾的配置文件更好用。虽然以“.yaml”也可以使用,但是坑太多,不建议使用
2、yaml配置文件规则写法如下:
yaml基本语法
1、大小写敏感
2、使用缩进表示层级关系
3、缩进时不允许使用tab,是允许使用空格
4、缩进时空格数目不重要,只要相同层级的元素左对齐即可
5、# 表示注释,从它开始到行尾被忽略
6、使用 --- 来进行每条信息的区别
---
name: Tom Smith
age: 37
spouse:
name: Jane Smith
age: 25
children:
- name: Jimmy Smith
age: 15
- name1: Jenny Smith
age1: 12
---
name: James
age: 20
---
name: Lily
age: 19
---
name: Silenthand Olleander
race: Human
traits: [ONE_HAND, ONE_EYE]
---
{age: 220, name1: James}
--- [Lily1, 129]
---
# 在python中会变成字典
name: 灰蓝
age: 0
job: Tester
---
# 下面格式读到Python里会是个列表
- 灰蓝
- 0
- Tester
---
# 下面格式读到Python里是个list里包含dict
- name: 灰蓝
age: 0
job: Tester
- name: James
age: 30
---
# 这个例子输出一个字典,其中value包括所有基本类型
str: "Hello World!"
int: 110
float: 3.141
boolean: true # or false
None: null # 也可以用 ~ 号来表示 null
# 使用strftime()方法来格式化时间参数
time: '2016-09-22 03:43:30'
date: '2016-09-22'
---
# 如果字符串没有空格或特殊字符,不需要加引号,但如果其中有空格或特殊字符,则需要加引号了
str: 灰蓝
str1: "Hello World"
str2: "Hello\nWorld"
---
# 这里要注意单引号和双引号的区别,单引号中的特殊字符转到Python会被转义,也就是到最后是原样输出了,双引号不会被Python转义,到最后是输出了特殊字符
str1: 'Hello\nWorld'
str2: "Hello\nWorld"
---
# & 和 * 用于引用
name: &name 灰蓝
tester: *name
---
# yaml使用!!进行强制转换
str: !!str 3.14
int: !!int "123"
---
- config:
- testset: "Tests using test app"
- test: # create entity
- name: "Basic get"
- url: "/api/person/"
- test: # create entity
- name: "Get single person"
- url: "/api/person/1/"
- test: # create entity
- name: "Get single person"
- url: "/api/person/1/"
- method: 'DELETE'
- test: # create entity by PUT
- name: "Create/update person"
- url: "/api/person/1/"
- method: "PUT"
- body: '{"first_name": "Gaius","id": 1,"last_name": "Baltar","login": "gbaltar"}'
- headers: {'Content-Type': 'application/json'}
- test: # create entity by POST
- name: "Create person"
- url: "/api/person/"
- method: "POST"
- body: '{"first_name": "Willim","last_name": "Adama","login": "theadmiral"}'
- headers: {Content-Type: application/json}
---
test_1_ip_api:
url: http://httpbin.org/ip
assert:
ResponseType:
- type
- dict
origin:
- type
- str
method: get
params: ''
desc: "\u6D4B\u8BD5httpbin\u7684ip\u63A5\u53E3\u8FD4\u56DE\u6B63\u5E38"
---
name: dashuaihang
---
platformName: Android
platformVersion: '7.0'
deviceName: A5RNW18316011440
appPackage: com.tencent.mm
appActivity: .ui.LauncherUI
automationName: Uiautomator2
unicodeKeyboard: true
resetKeyboard: true
noReset: true
chromeOptions:
androidProcess: com.tencent.mm:tools
---
- 1
- 2
- 3
- 4
- 5
- 6
--- "\u5929\u884C\u5065\u3002\u541B\u5B50\u4EE5\u81EA\u5F3A\u4E0D\u606F"
---
- 1
- 3
- 4
- 433
- 53
代码封装如下:
import os
from ruamel import yaml
import ruamel
import json
import warnings
import datetime
"""对yaml配置文件进行封装"""
class TestYaml(object):
def __init__(self, file):
"""
get target file
"""
self.file = os.path.join(
os.path.dirname(os.path.realpath(__file__)), file)
def read_yaml_file(self):
"""
to read yaml data
"""
warnings.simplefilter('ignore', ruamel.yaml.error.UnsafeLoaderWarning)
with open(self.file, 'r', encoding='utf-8') as f:
result = yaml.load_all(f.read())
for i in result:
print()
print("*****************************************")
print()
if isinstance(i, dict):
print(json.dumps(
i,
ensure_ascii=False,
sort_keys=True,
indent=4,
separators=(',', ':')))
else:
print(i)
def write_yaml_file(self, *data):
"""
write yaml data
"""
try:
with open(self.file, 'w', encoding='utf-8') as f:
yaml.dump_all(
data, f,
Dumper=yaml.RoundTripDumper) # Dumper=yaml.RoundTripDumper
print("数据写入成功!")
except Exception as e:
print(f"发生错误{e}")
finally:
f.close()
if __name__ == "__main__":
y = TestYaml("yaml_test.yml")
"""将参数写入对应的yaml配置文件中"""
test_data1 = {
"test_1_ip_api": {
"url":
"http://httpbin.org/ip",
"assert": {
"ResponseType": ["type", "dict"],
"origin": ["type", "str"]
},
"method":
"get",
"params":
"",
"desc":
"\u6d4b\u8bd5httpbin\u7684ip\u63a5\u53e3\u8fd4\u56de\u6b63\u5e38"
}
}
test_data2 = {"name": "dashuaihang"}
test_data3 = {
'platformName': 'Android',
'platformVersion': '7.0',
'deviceName': 'A5RNW18316011440',
'appPackage': 'com.tencent.mm',
'appActivity': '.ui.LauncherUI',
'automationName': 'Uiautomator2',
'unicodeKeyboard': True,
'resetKeyboard': True,
'noReset': True,
'chromeOptions': {'androidProcess': 'com.tencent.mm:tools'}
}
test_data4 = [1, 2, 3, 4, 5, 6]
test_data5 = """天行健。君子以自强不息"""
test_data6 = (1, 3,4,433,53)
test_data7 = {
'str': 'Hello World!',
'int': 110,
'float': 3.141,
'boolean': True,
'time': datetime.datetime(2016, 9, 22, 3, 43, 30, 200000).strftime('%Y-%m-%d %H:%M:%S'),
'date': datetime.date(2016, 9, 22).strftime('%Y-%m-%d')
}
"""读取yaml配置文件内的参数"""
y.read_yaml_file()
"""将参数写入对应的yaml配置文件中"""
# y.write_yaml_file(test_data1, test_data2, test_data3, test_data4,test_data5, test_data6, test_data7)