python yamlファイルを読み込んだ後、ローカルへの書き込みを変更

983 ワード

まずpip install ruamelをインストール.yaml yamlファイルの変更に使用
#coding:utf-8
from ruamel import yaml

def up_yml(ip_server):
    with open('./../docker-compose-demo.yml', encoding="utf-8") as f:
        content = yaml.load(f, Loader=yaml.RoundTripLoader)
        #   yml      
        content['service']['memo_query']['server_ip'][0] = 'mysql_host={}'.format(ip_server)
    with open('./../docker-compose.yml', 'w', encoding="utf-8") as nf:
        yaml.dump(content, nf, Dumper=yaml.RoundTripDumper)

if __name__ == '__main__':
    up_yml(ip_server='0.0.0.0')

変更前:
version: '1'
service:
  memo_query:
    image: python:2.0
    restart: always
    server_ip:
    - mysql_host=192.168.1.1

変更後:
version: '1'
service:
  memo_query:
    image: python:2.0
    restart: always
    server_ip:
    - mysql_host=0.0.0.0