快译通类型变量中使用字符串变量

问题描述 投票:1回答:3

我们有3个不同的数据中心环境,以供参考,让我们说,美国,加拿大和IN。所有这三个有其他2不同puppetdb主因此而自动一些东西,我想一个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"
}
}

现在,主脚本,在这里我想使用一个名为“myenv”变量,这将是美国,还是CA或者在一个指的是字典类型的配置的关键。不过,我不断收到如下错误:

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

下面您参考脚本本身:

#!/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']

我如何使用字典作为重点中的字符串类型变量?

编辑:请注意,这在我的问题可能丢失所有必要的缺口,都被照顾,因为我使用PyCharm。

python
3个回答
0
投票
Traceback (most recent call last):
  File "./get_hname.py", line 94, in <module>
    print (config[myenv.upper()]['PDB'])
KeyError: 'NONE'

这是否意味着myenv变量是在那一刻串'None'。核实。


0
投票

您需要修改add_arguments删除nargs='*'即给予ENV以列表的形式见下面的例子:

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

请参阅更多信息this文件。


0
投票

OK乡亲,我发现我在做什么错。我使用的参数

type=str and nargs='*'

这就是为什么我正面临一个类型不匹配和获得的输出为[“US”]代替美国(或CA或IN)。一旦我删除了,东西都工作正常。

谢谢大家的指针。这帮助。

© www.soinside.com 2019 - 2024. All rights reserved.