【发布时间】:2021-12-22 18:31:56
【问题描述】:
试图访问字典中的数据让我头疼。我不确定我所说的字典是否真的是正确的,但至少下面的结构不会给我错误。
来自文件configuration.py
...
appList = {
"app1": {
"appCode": "xyz",
"appName": "name1",
"appType": "ChromeWebApp",
"appAddress": '/opt/google/chrome/google-chrome \"--profile-directory=Profile {0}\"'.format(v.profil),
"appID": " --app-id=abcdefgh123456",
"appRemoteDebug": ' --remote-debugging-port=9222',
"functions": {
"action1",
"action2",
"action3"}
},
"app14": {
"appCode": "xyz",
"appName": "name1",
"appType": "python",
"appAddress": '/bin/python3 /home/folder/app.py',
"appID": " --app-id=qwertyui48965",
"appRemoteDebug": ' --remote-debugging-port=9222',
"functions": {
"action17",
"action29",
"action39"}
}
}
def checkUser(dico, user):
if user in dico:
return True
return False
def checkArgs(dico, webapp, functions, function):
if webapp in dico:
if functions in dico[webapp]:
if function in dico[webapp][functions]:
return True
return False
脚本 main.py 需要 3 个参数
parser = argparse.ArgumentParser(...)
group = parser.add_mutually_exclusive_group()
parser.add_argument("-u", type=str, dest='u', help="the user")
parser.add_argument("-a", type=str, dest='a', help="the app")
parser.add_argument("-f", type=str, dest='f', help="the function")
args = parser.parse_args()
然后根据位于第一个文件 (config.py) 中的字典检查参数 和与参数匹配的数据将被访问,并将提供第三个文件 variables.py
def varDefining():
v.user = args.u
v.appCode = args.a
v.appFunc = args.f
v.profil = [c.userList][v.user]["profil"]
v.appID = [c.appList][v.appCode]["appID"]
v.appPath = [c.appList][v.appCode]["appAddress"]
v.appRemoteDebug = [c.appList][v.appCode]["appRemoteDebug"]
if args.quiet:
if c.checkUser(c.userList, args.u) == True:
if c.checkArgs(c.appList, args.a, "functions", args.f) == True:
varDefining()
在几千次尝试和错误中,我曾经收到以下错误消息:
TypeError:列表索引必须是整数或切片,而不是 NoneType
我可以通过以下方式获得它: print([c.appList][args.a]) 这很可能意味着我访问数据的方式不正确,或者字典本身的格式不正确......
我实际上是在尝试正确编码我的 Python 脚本,这就是为什么存在三个文件:main、config 和 variables,这可能是一种错误的方式,我没有在我自己想象的教程中看到这一点。因此,我的第一个需求显然是摆脱列表索引错误,但欢迎任何关于我的编码和建议风格的 cmet,甚至是关于该主题的文档链接。
谢谢
【问题讨论】:
-
错误发生在哪一行代码?并且还将整个代码包含在一个块中。
-
我确定错误出现在
varDefining()方法中,因为您没有访问字典中的元素,而是访问了c.userList中的元素,这可能是一个列表。如果我错了,请纠正我。 -
无关:
def checkUser(dico, user): return user in dico -
来自解析器的
args.a将是默认的None,或者是用户提供的字符串。
标签: python dictionary argparse