使用 argparse 和 python 接受字典作为参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18608812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:14:10  来源:igfitidea点击:

Accepting a dictionary as an argument with argparse and python

pythondictionaryargparse

提问by user2745896

I'm trying to accept an argument of type=dict with argparse but no matter the input it gives an error of invalid dict value.

我正在尝试使用 argparse 接受 type=dict 的参数,但无论输入如何,它都会给出无效 dict 值的错误。

#!/usr/bin/env python

import argparse

MYDICT = {'key': 'value'}

parser = argparse.ArgumentParser()
parser.add_argument("-m", "--mydict", action="store",
                    required=False, type=dict,
                    default=MYDICT)

args = parser.parse_args()

print args.mydict

This is what happens when I try and pass a dictionary to the script

当我尝试将字典传递给脚本时会发生这种情况

./argp.py -m "{'key1': 'value1'}"
usage: argp.py [-h] [-m MYDICT]
argp.py: error: argument -m/--mydict: invalid dict value: "{'key1': 'value1'}"

Looking at the documents I would think that this would be possible.

查看文件,我认为这是可能的。

http://docs.python.org/dev/library/argparse.html

http://docs.python.org/dev/library/argparse.html

“Any object that supports the in operator can be passed as the choices value, so dict objects, set objects, custom containers, etc. are all supported.”

“任何支持 in 运算符的对象都可以作为选择值传递,因此字典对象、集合对象、自定义容器等都被支持。”

采纳答案by Michael Aquilina

I do not think it is possible to pass a dictionary as an argument in the command line because there doesn't exist a conversion function from string to dict (EDIT: A hack ispossible, see below). What you are essentially telling python to do is:

我认为不可能在命令行中将字典作为参数传递,因为不存在从字符串到字典的转换函数(编辑:黑客可能的,见下文)。你本质上告诉python要做的是:

dict("{'key1': 'value1'}")

Which if you try it out in the python console, does not work.

如果您在 python 控制台中尝试它,则不起作用。

What the phrase:

什么成语:

"Any object that supports the in operator can be passed as the choices value, so dict objects, set objects, custom containers, etc. are all supported."

“任何支持 in 运算符的对象都可以作为选择值传递,因此字典对象、集合对象、自定义容器等都得到支持。”

refers to is the choicesargument that can be passed with the add_argumentfunction - not to the typeargument.

指的是可以通过add_argument函数传递的选择参数- 而不是类型参数。

Your best bet is to probably accept your argument as a string and then convert it using the jsoncapabilities of python:

您最好的选择是将您的参数作为字符串接受,然后使用python的json功能将其转换:

parser.add_argument('-m', '--my-dict', type=str)
args = parser.parse_args()

import json
my_dictionary = json.loads(args.my_dict)

You can then pass a dictionary in the form of a string. You can try the json encoder/decoder out for yourself in the python console to see how it works:

然后,您可以以字符串的形式传递字典。您可以在 python 控制台中亲自尝试 json 编码器/解码器,看看它是如何工作的:

>>>json.loads('{"value1":"key1"}')
{u'value1': u'key1'}

EDIT: hpaulj has pointed out to me that you can "hack" the typeparameter by passing it json.loads.

编辑:hpaulj 向我指出,您可以通过传递json.loads来“破解”类型参数。

import json
parser.add_argument('-d', '--my-dict', type=json.loads)
args = parse.parse_args()

mydict = args.my_dict  # Will return a dictionary

NOTE: The input format you pass is notthe same as python dictionary but is probably similar enough for your use case.

注意:您传递的输入格式是一样的Python字典,但可能是为您的使用情况类似的就够了。

The reason this works is actually quite interesting because internally argparse will just use the parameter value as a function to convert the argument. i.e. if type=int then it will use int(arg) or if type=json.loads then json.loads(arg)

这样做的原因实际上很有趣,因为在内部 argparse 只会将参数值用作转换参数的函数。即如果 type=int 那么它将使用 int(arg) 或者如果 type=json.loads 那么 json.loads(arg)

This also means that you can pass any function which takes a single parameter in as the argument to type and perform custom conversions if you need to :)

这也意味着您可以传递任何将单个参数作为参数输入的函数,并在需要时执行自定义转换:)