Python 讀取配置文件常用幾種方式


  引言

  我們在設計自動化測試框架的時候,經常使用到配置文件,而配置文件種類有很多,常見的配置文件格式有很多中:ini、yaml、xml、properties、txt、py等。

  配置文件ini

  雖然配置文件放置一些公共的內容,比如說環境、路徑、參數等。但也可以放測試數據,比如說接口一些信息,但不建議這樣做。

  下面看python讀取配置文件ini的實例:

1、新建配置文件ini,符號:;是注釋。

;測試配置文件
[api]
url = "www."
method = get
header =
data =
resp_code = 200
resp_json = {}

  

2、創建讀取ini的py文件,最好與ini配置文件同一層級目錄:

from configparser import ConfigParser
import os

class ReadConfigFile(object):
    def read_config(self):
        conn = ConfigParser()
        file_path = os.path.join(os.path.abspath('.'),'config_test.ini')
        if not os.path.exists(file_path):
            raise FileNotFoundError("文件不存在")

        conn.read(file_path)
        url = conn.get('api','url')
        method = conn.get('api','method')
        header = conn.get('api','header')
        data = conn.get('api','data')
        resp_code = conn.get('api','resp_code')
        resp_json = conn.get('api','resp_code')

        return [url,method,header,data,resp_code,resp_json]

rc = ReadConfigFile()
print(rc.read_config())

  

運行結果:

 

 

 

  配置文件yaml

  上面已經介紹配置文件ini讀取方法,現在講yaml文件讀取。

  yaml [ˈjæməl]: Yet Another Markup Language :另一種標記語言。yaml 是專門用來寫配置文件的語言。

1、yaml文件規則

  1.區分大小寫;

  2.使用縮進表示層級關系;

  3.使用空格鍵縮進,而非Tab鍵縮進

  4.縮進的空格數目不固定,只需要相同層級的元素左側對齊;

  5.文件中的字符串不需要使用引號標注,但若字符串包含有特殊字符則需用引號標注;

  6.注釋標識為#

2、yaml文件數據結構

  1.對象:鍵值對的集合(簡稱 "映射或字典")
鍵值對用冒號 “:” 結構表示,冒號與值之間需用空格分隔

  2.數組:一組按序排列的值(簡稱 "序列或列表")
數組前加有 “-” 符號,符號與值之間需用空格分隔

  3.純量(scalars):單個的、不可再分的值(如:字符串、bool值、整數、浮點數、時間、日期、null等)
None值可用null可 ~ 表示

  yaml文件基本數據類型

# 純量
s_val: name              # 字符串:{'s_val': 'name'}
spec_s_val: "name\n"    # 特殊字符串:{'spec_s_val': 'name\n'
num_val: 31.14          # 數字:{'num_val': 31.14}
bol_val: true           # 布爾值:{'bol_val': True}
nul_val: null           # null值:{'nul_val': None}
nul_val1: ~             # null值:{'nul_val1': None}
time_val: 2018-03-01t11:33:22.55-06:00     # 時間值:{'time_val': datetime.datetime(2018, 3, 1, 17, 33, 22, 550000)}
date_val: 2019-01-10    # 日期值:{'date_val': datetime.date(2019, 1, 10)}

  

  簡單讀取:

  前提條件:python中讀取yaml文件前需要安裝pyyaml和導入yaml模塊。

import yaml

doc = """
---
"data":
 "id":
   -
     123
---
"data":
 "name":
   -
     "測試"
 "age": 2
   
"""
doc2 = """
---
"data":
 "id":
   -
     123


"""
# 方法1
data = yaml.load(doc2,Loader=yaml.FullLoader)
print(type(data))
print(data)

get_dict = []
# 迭代器
data2 = yaml.load_all(doc,Loader=yaml.FullLoader)
for i in data2:
    print(i)
    get_dict.append(i)

print(get_dict[1]['data']['age'] == 2)

  

運行結果:

 

 

 這里有個問題點:Loader=yaml.FullLoader,解釋如下:

"""
1.
yaml.load(f, Loader=yaml.FullLoader)

2.
yaml.warnings({'YAMLLoadWarning': False})  # 全局設置警告,不推薦

Loader的幾種加載方式

BaseLoader - -僅加載最基本的YAML

SafeLoader - -安全地加載YAML語言的子集。建議用於加載不受信任的輸入。

FullLoader - -加載完整的YAML語言。避免任意代碼執行。這是當前(PyYAML5.1)默認加載器調用
yaml.load(input)(發出警告后)。

UnsafeLoader - -(也稱為Loader向后兼容性)原始的Loader代碼,可以通過不受信任的數據輸入輕松利用。

"""

  

  讀取單個yaml文檔

  這里使用python的open方法打開文件,使用yaml的load方法可以將單個yaml文檔中數據轉化成字典或列表。

  新建配置文件test_config02:

---
data:
  id: 1
  name: {
         age: 2}
  other:
    -
      height: 3

  新建讀取配置文件py:

# 單個文檔
import yaml
import os


def get_yaml_data(yaml_file):
    # 打開yaml文件
    print("***獲取yaml文件數據***")
    file = open(yaml_file, 'r', encoding="utf-8")
    file_data = file.read()
    file.close()

    print(file_data)
    print("類型:", type(file_data))

    # 將字符串轉化為字典或列表
    print("***轉化yaml數據為字典或列表***")
    data = yaml.load(file_data,Loader=yaml.FullLoader)
    print(data)
    print("類型:", type(data))
    return data


current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "test_config02")
get_yaml_data(yaml_path)

  

運行結果:

 

 

 

  讀取多個yaml文檔

多個文檔在一個yaml文件,使用 --- 分隔方式來分段

新建一個yaml配置文件test_config:

---
data:
  id: 1
  name: {
         age: 2}
  other:
    -
      height: 3

---
id: 2
name: "測試用例2"

  

編寫讀寫yaml函數:

import yaml
import os

def get_yaml_load_all(filename):
    with open(filename,'r') as fp:
        file_data = fp.read()
        fp.close()
        print("類型: ",type(file_data))
        all_data = yaml.load_all(file_data,Loader=yaml.FullLoader)
        print("類型: ",type(all_data))
        for data in all_data:
            print(data)

current_path = os.path.abspath('.')
file_path = os.path.join(current_path,'test_config')
print(file_path)
get_yaml_load_all(file_path)

  

運行結果:

 

 

 

  配置文件xml

  python讀取xml文件可能自動化測試平時用的少,這里介紹一下:

  這個xml文件內容如下:

<collection shelf="New Arrivals">
<movie title="Enemy Behind">
   <type>War, Thriller</type>
   <format>DVD</format>
   <year>2003</year>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
   <type>Anime, Science Fiction</type>
   <format>DVD</format>
   <year>1989</year>
   <rating>R</rating>
   <stars>8</stars>
   <description>A schientific fiction</description>
</movie>
   <movie title="Trigun">
   <type>Anime, Action</type>
   <format>DVD</format>
   <episodes>4</episodes>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Vash the Stampede!</description>
</movie>
<movie title="Ishtar">
   <type>Comedy</type>
   <format>VHS</format>
   <rating>PG</rating>
   <stars>2</stars>
   <description>Viewable boredom</description>
</movie>
</collection>

 

  讀取代碼:

# coding=utf-8
import xml.dom.minidom
from xml.dom.minidom import parse

DOMTree = parse('config')
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
    print("Root element : %s" % collection.getAttribute("shelf"))

# 在集合中獲取所有電影
movies = collection.getElementsByTagName("movie")

# 打印每部電影的詳細信息
for movie in movies:
    print("*****Movie*****")
    if movie.hasAttribute("title"):
        print("Title: %s" % movie.getAttribute("title"))

    type = movie.getElementsByTagName('type')[0]
    print("Type: %s" % type.childNodes[0].data)
    format = movie.getElementsByTagName('format')[0]
    print("Format: %s" % format.childNodes[0].data)
    rating = movie.getElementsByTagName('rating')[0]
    print("Rating: %s" % rating.childNodes[0].data)
    description = movie.getElementsByTagName('description')[0]
    print("Description: %s" % description.childNodes[0].data)

  

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM