简体   繁体   English

在Dict类型变量中使用字符串变量

[英]Using string variable within Dict type variable

We have 3 different Datacenter environments, for reference, let us say, US, CA and IN. 我们有3种不同的数据中心环境,以供参考,例如US,CA和IN。 All three have a puppetdb master different to the other 2. So while automating some stuff, I want to a config.json file like below and reference it from the main code based on the parameters passed: 这三个都有一个与其他2个不同的puppetdb master。因此,在自动化某些东西的同时,我想要一个config.json文件,如下所示,并根据传递的参数从主代码中引用它:

// config.json
{
"DEFAULT": {
    "LOGFILE": "log/get_hname.log",
    "LOCKDIR": "include/LOCK",
    "NOOPRUN": "0"
},
"US": {
    "PDB": "puppetdb100.us",
    "VRFFILE": "include/vrf.txt",
    "FQDN": "us.livevox"
},
"CA": {
    "PDB": "puppet.ca.livevox.net",
    "FQDN": "ca.livevox"
},
"IN": {
    "PDB": "puppet100.in.livevox.net",
    "FQDN": "in.livevox"
}
}

Now, for the main script, where I am trying to use a variable called "myenv", which would be one of US, or CA or IN to refer the key in the config which is of dict type. 现在,对于主脚本,我试图使用一个名为“ myenv”的变量,该变量将是US或CA或IN之一,以引用dict类型的配置中的键。 But I keep getting the error as below: 但是我一直收到如下错误:

Traceback (most recent call last):
  File "./get_hname.py", line 94, in <module>
    print (config[myenv.upper()]['PDB'])
KeyError: 'NONE'

The script itself for your reference below: 该脚本本身供您参考,如下:

#!/usr/bin/env python

import argparse
import json
import sys 
import os
import logging
import time
from argparse import ArgumentParser

# Where Config File lives --------
CONFFILE = "include/get-hname-cfg.json"
# - DO NOT EDIT BELOW THIS LINE --

with open(CONFFILE, 'r') as f:
config = json.load(f)

logfile = config['DEFAULT']['LOGFILE']
myarguments = argparse.ArgumentParser(description="Arguments for Name Builder", usage="%(prog)s [options]")
myarguments.add_argument("-e", "--env", type=str, metavar="environment", nargs='*', help="Environment")
myarguments.add_argument("-t", "--type", type=str, metavar="servertype", nargs='*', help="Server type")
myarguments.add_argument("-n", "--noop", action="store_true", help="Stimulate the whole run, but don't execute. Similar to noop")
myarguments.parse_args()
args = myarguments.parse_args()

if not args.env and not args.type:
    myarguments.print_help(sys.stderr)

myenv = str(args.env).lower()


pdbhost = "config" +myenv.upper()+ "['PDB']"
print ("%s" %(pdbhost))

if config[myenv.upper()]['PDB'] in globals():
puppetdbhost = config[myenv.upper()]['PDB']

How can I use the string type variable within a dict as a key? 如何将字典中的字符串类型变量用作键?

EDIT : Please note, all necessary indentations which maybe missing in my question, have all been taken care of, since I'm using PyCharm. 编辑:请注意,自从我使用PyCharm以来,我的问题中可能缺少的所有必要缩进都已得到处理。

you need to modify your add_arguments remove nargs='*' which is giving env in list form see below example: 您需要修改add_arguments remove nargs='*' ,以列表形式提供env,请参见以下示例:

myarguments.add_argument("-e", "--env", type=str, metavar="environment", help="Environment")

refer this document for more info. 请参阅文档以获取更多信息。

Traceback (most recent call last):
  File "./get_hname.py", line 94, in <module>
    print (config[myenv.upper()]['PDB'])
KeyError: 'NONE'

It's mean that myenv variable is string 'None' in that moment. 这意味着那一刻myenv变量是字符串'None' Check it. 核实。

OK folks, I found what I was doing wrong. 好的,伙计们,我发现我做错了。 The arguments I was using 我正在使用的参数

type=str and nargs='*'

which is why I was facing a type mismatch and getting the output as ['US'] instead of US (or CA or IN). 这就是为什么我遇到类型不匹配并以['US']而不是US(或CA或IN)的形式输出的原因。 Once I removed that, things are working fine. 一旦我删除了它,一切就很好了。

Thank you all for your pointers. 谢谢大家的指点。 That helped. 有帮助。

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

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