最近Yaml(YAML Ain’t a Markup Language)在python編程裡算是比較流行的配置項方法。主要是把變量寫進yaml做配置文件,然後python腳本從yaml文件裏面取得變量,用來表達資料序列的格式,讓程式可讀性變高,而且通過縮進表示結構,這一點與python不謀而合。
安裝方法:pip install PyYaml
1. Dict: Dict 是最基本的格式,任何有“:” 的地方都會以 Dict 來呈現
resources:
cpu: .5
memory_gb: 1
disk_size_gb: 10
Parse 後:
‘resources’: {‘disk_size_gb’: 10, ‘cpu’: 0.5, ‘memory_gb’: 1}
2. List: 透過在每個選項前面加一個 “ — “ 號來實現
skip_files:
— ^(.*/)?#.*#$
— ^(.*/)?.*~$
— ^(.*/)?.*\.py[co]$
— ^(.*/)?.*/RCS/.*$
— ^(.*/)?\..*$
Parse 後:
'skip_files': [‘^(.*/)?#.*#$’, ‘^(.*/)?.*~$’, ‘^(.*/)?.*\\.py[co]$’, ‘^(.*/)?.*/RCS/.*$’, ‘^(.*/)?\\..*$’, ‘bin/’, ‘__pycache__/’, ‘lib/’, ‘include/’, ‘pip-selfcheck.json’]
細心的讀者應該有注意到,在 parse 過程中會自動辨識欄位屬性,例如 cpu 數就會被 parse 成 數值,而下方的 regular expression 就辨識成字串.
3. 另外也可以儲存分行的文字:
test_block: |
first line
second line
parse 後,每個分行後會加上\n的分隔符號
‘test_block’: ‘first line\nsecond line\n’
4. 另外一種分行文字
test_block1: >
first line
second line
parse 後,會變成同一行,以空白區隔
'test_block1': ‘first line second line\n’
5. 讀取 Yaml 檔
python 內建 yaml package,使用方式也很簡單.
例如有個檔案長這樣:
runtime_config:
python_version: 3
env_variables:
SQLALCHEMY_DATABASE_URI: >-
mysql+mysqlconnector://qoo:123456@www.graffitalk.com
USER: ‘AAA BBB CCC DDD’
WORKPATH: /home/graffitalk/workspace
test_block: |
first line
second line
test_block1: >
first line
second line
resources:
cpu: .5
memory_gb: 1
disk_size_gb: 10
skip_files:
— ^(.*/)?#.*#$
— ^(.*/)?.*~$
— ^(.*/)?.*\.py[co]$
— ^(.*/)?.*/RCS/.*$
— ^(.*/)?\..*$
— bin/
— __pycache__/
— lib/
— include/
— pip-selfcheck.json
在 Python 中只要
import yaml
with open(“app.yaml”, “r”) as stream:
data = yaml.load(stream)
data 會以 dictionary 的方式呈現:
{‘resources’: {‘disk_size_gb’: 10, ‘cpu’: 0.5, ‘memory_gb’: 1}, ‘test_block’: ‘first line\nsecond line\n’, ‘runtime_config’: {‘python_version’: 3}, ‘env_variables’: {‘USER’: ‘AAA BBB CCC DDD’, ‘WORKPATH’: ‘/home/graffitalk/workspace’, ‘SQLALCHEMY_DATABASE_URI’: ‘mysql+mysqlconnector://qoo:123456@www.graffitalk.com'}, ‘test_block1’: ‘first line second line\n’, ‘env’: ‘flex’, ‘skip_files’: [‘^(.*/)?#.*#$’, ‘^(.*/)?.*~$’, ‘^(.*/)?.*\\.py[co]$’, ‘^(.*/)?.*/RCS/.*$’, ‘^(.*/)?\\..*$’, ‘bin/’, ‘__pycache__/’, ‘lib/’, ‘include/’, ‘pip-selfcheck.json’], ‘service’: ‘default’, ‘entrypoint’: ‘python app.py’, ‘runtime’: ‘python’}
參考
https://medium.com/bryanyang0528/%E4%BD%BF%E7%94%A8-python-%E8%AE%80%E5%8F%96-yaml-%E6%AA%94%E6%A1%88-d3f413d7dd6
沒有留言:
張貼留言