How can variables be called in YAML in Python?

In Python, the yaml module can be used to parse and work with YAML files. To reference variables, you can use the syntax ${var_name} in the YAML file and then parse the YAML file in Python code by passing a dictionary containing variable values.

Here is an example:

Define variables in a YAML file (e.g. config.yaml).

database:
  host: ${db_host}
  port: ${db_port}

Parse a YAML file in Python code and pass variable values.

import yaml

# 定义变量值
var_values = {
    'db_host': 'localhost',
    'db_port': 3306
}

# 加载并解析YAML文件
with open('config.yaml') as file:
    config = yaml.safe_load(file)

# 使用变量值
db_host = config['database']['host']
db_port = config['database']['port']

print(f"数据库主机: {db_host}")
print(f"数据库端口: {db_port}")

In this way, by passing the values of the var_values dictionary, variables from a YAML file can be accessed in Python code. The output result will be:

数据库主机: localhost
数据库端口: 3306
广告
Closing in 10 seconds
bannerAds