共計 637 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 yaml
模塊來解析和使用 YAML 文件。要調用變量,可以在 YAML 文件中使用 ${var_name}
的語法,然后在 Python 代碼中通過傳遞一個包含變量值的字典來解析 YAML 文件。
下面是一個示例:
在 YAML 文件(例如config.yaml
)中定義變量:
database:
host: ${db_host}
port: ${db_port}
在 Python 代碼中解析 YAML 文件并傳遞變量值:
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}")
這樣,通過傳遞 var_values
字典的值,就可以在 Python 代碼中調用 YAML 文件中的變量。輸出結果將會是:
數據庫主機: localhost
數據庫端口: 3306
丸趣 TV 網 – 提供最優質的資源集合!
正文完