用argparse和python接受字典作为参数 [英] Accepting a dictionary as an argument with argparse and python

查看:1179
本文介绍了用argparse和python接受字典作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

会认为这是可能的。

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

任何支持in运算符的对象都可以作为选择值传递,所以支持dict对象,设置对象,自定义容器等。

"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."

推荐答案

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

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 is possible, see below). What you are essentially telling python to do is:

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

如果您在python控制台中尝试,则无法使用。

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

短语:

支持in运算符的任何对象都可以作为选择值传递,所以dict对象设置对象,自定义容器等都是支持的。

是指可以传递的选项参数 add_argument 函数 - 不是类型参数。

refers to is the choices argument that can be passed with the add_argument function - not to the type argument.

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

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

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

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

然后,您可以以字符串的形式传递字典。您可以在python控制台中尝试使用json编码器/解码器来查看它的工作原理:

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:

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

编辑:hpaulj已经指出,您可以通过传递 json来骇客类型参数。负载

EDIT: hpaulj has pointed out to me that you can "hack" the type parameter by passing it 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

它的工作原理实际上很有趣,因为内部的argparse将只是使用参数值作为函数来转换参数。即如果type = int,那么它将使用int(arg)或如果type = json.loads然后json.loads(arg)

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)

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

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 :)

这篇关于用argparse和python接受字典作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆