简体   繁体   English

Python 如何从配置 toml 文件中获取值

[英]Python how to get value from config toml file

Hi I am trying to get the value from config.toml file.您好我正在尝试从 config.toml 文件中获取值。 Below is the config.toml file:下面是 config.toml 文件:

path.repo_uat7="/home/developer/user1"
path.repo_uat12="/home/repo/user21"
database.hostname.uat7="dbname7"
database.hostname.uat12="dbname12"
database.port="1825"
db.cluster.nodes=["cluster1:15382","cluster2:15382"]

I tried getting the value of path.repo_uat7 and path.repo_uat12 by the below python script:我尝试通过以下 python 脚本获取 path.repo_uat7 和 path.repo_uat12 的值:

#!/usr/bin/env python3
import toml
import sys, os

data = toml.load("uat7.toml")
print (toml.dumps(data))

desc = str(sys.argv[1])
st = desc.split(".")
st1 = st[0]
st2 = st[1]


for k1, v1 in data.items():
    if k1 == st1:
     for k2, v2 in v1.items():
       if k2 == st2:
         print(v2)

This is how I run my code: python getvar.py path.repo_uat7.这就是我运行代码的方式:python getvar.py path.repo_uat7。 I am getting output as我得到 output 作为

/home/developer/user1

But what if I want to get the database or db.cluster.nodes, how to iterate multiple times, I am not getting perfect solution.但是如果我想获取数据库或者db.cluster.nodes,如何迭代多次,我没有得到完美的解决方案。 Please help.请帮忙。

You don't have to iterate.您不必重复。 You can index data directly with the given keys.您可以使用给定的键直接索引data Replace the for loop withfor循环替换为

print(data[st1][st2])

and you get the same output.你得到相同的 output。

Similarly, you can write data['database']['hostname']['uat7'] to get "dbname7" , etc.同样,您可以编写data['database']['hostname']['uat7']来获取"dbname7"等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM