yaml是一个专门用来写配置文件的语言。
1. yaml文件规则
2. yaml文件数据结构
3、安装yaml
pip install pyyaml
4、使用yaml
from ruamel import yaml
5、用途:
在我们做自动化测试中,可用作配置文件,配置一些服务器域名、mysql配置、登录信息、toekn等很方便快速读取
desired_caps = {
'platformName':'Android哈哈哈',#移动设备系统IOS或Android
'platformVersion':'7.1.2',#Android手机系统版本号
'deviceName':'852',#手机唯一设备号
'app':'C:\\Users\\wangli\\Desktop\\kbgz-v5.9.0-debug.apk',#APP文件路径
'appPackage':'com',#APP包名
'appActivity':'cui.setup.SplashActivity',#设置启动的Activity
'noReset':'True',#每次运行不重新安装APP
'unicodeKeyboard':'True', #是否使用unicode键盘输入,在输入中文字符和unicode字符时设置为true
'resetKeyboard':'True',#隐藏键盘
'autoGrantPermissions':'True',
'autoAcceptAlerts':["python","c++","java"],
'chromeOptions': {'androidProcess': 'com.tencent.mm:tools'}
}
with open("test.yaml","w",encoding="utf-8") as f:
yaml.dump(desired_caps,f,Dumper=yaml.RoundTripDumper)
写入文件如下:
deviceName: '852'
unicodeKeyboard: 'True'
autoAcceptAlerts:
- python
- c++
- java
autoGrantPermissions: 'True'
platformVersion: 7.1.2
platformName: "Android\u54C8\u54C8\u54C8"
app: C:\Users\wangli\Desktop\kbgz-v5.9.0-debug.apk
appPackage: com
chromeOptions:
androidProcess: com.tencent.mm:tools
appActivity: cui.setup.SplashActivity
noReset: 'True'
resetKeyboard: 'True'
三、将列表写入yaml文件
list=['python','java','c++','C#',{'androidProcess': 'com.tencent.mm:tools'},["python","c++","java"]]
with open("test.yaml","w",encoding="utf-8") as f:
yaml.dump(list,f,Dumper=yaml.RoundTripDumper)
写入文件如下:
- python
- java
- c++
- C#
- androidProcess: com.tencent.mm:tools
- - python
- c++
- java
四、读取yaml文件中字典
用python读取yaml文件案例,先用open方法读取文件数据,再通过load方法转成字典,这个load跟json里面的load是相似的
yaml文件内容
chromeOptions:
androidProcess: com.tencent.mm:tools
appActivity: cui.setup.SplashActivity
noReset: 'True'
app: C:\Users\wangli\Desktop\kbgz-v5.9.0-debug.apk
appPackage: com
platformVersion: 7.1.2
resetKeyboard: 'True'
autoGrantPermissions: 'True'
deviceName: '852'
autoAcceptAlerts:
- python
- c++
- java
unicodeKeyboard: 'True'
platformName: "Android\u54C8\u54C8\u54C8"
读取yaml
with open('test.yaml', 'r', encoding='utf-8') as f:
print(yaml.load(f.read(),Loader=yaml.Loader))
读出内容如下
{'platformVersion': '7.1.2', 'resetKeyboard': 'True', 'appPackage': 'com', 'autoAcceptAlerts': ['python', 'c++', 'java'], 'autoGrantPermissions': 'True', 'deviceName': '852', 'appActivity': 'cui.setup.SplashActivity', 'unicodeKeyboard': 'True', 'noReset': 'True', 'platformName': 'Android哈哈哈', 'app': 'C:\\Users\\wangli\\Desktop\\kbgz-v5.9.0-debug.apk', 'chromeOptions': {'androidProcess': 'com.tencent.mm:tools'}}
五、读取yaml文件中列表
yaml文件内容
- python
- java
- c++
- C#
- androidProcess: com.tencent.mm:tools
- - python
- c++
- java
读取yaml文件
with open('test.yaml', 'r', encoding='utf-8') as f:
print(yaml.load(f.read(),Loader=yaml.Loader))
读取出内容如下
"C:\Program Files\Python35\python.exe" C:/Users/wangli/PycharmProjects/Test/Test/test.py
['python', 'java', 'c++', 'C#', {'androidProcess': 'com.tencent.mm:tools'}, ['python', 'c++', 'java']]
Process finished with exit code 0