【发布时间】:2013-06-11 04:59:55
【问题描述】:
我尝试使用 argparse 来了解它是如何解析给定列表的:
parser = argparse.ArgumentParser()
parser.add_argument('--ls', nargs='*', type=str, default = [])
Out[92]: _StoreAction(option_strings=['--ls'], dest='ls', nargs='*', const=None, default=[], type=<type 'str'>, choices=None, help=None, metavar=None)
args = parser.parse_args("--ls 'tomato' 'jug' 'andes'".split())
args
Out[94]: Namespace(ls=["'tomato'", "'jug'", "'andes'"])
args.ls
Out[96]: ["'tomato'", "'jug'", "'ande'"]
args.ls[0]
Out[97]: "'tomato'"
eval(args.ls[0])
Out[98]: 'tomato'
Q1:上述方法可行,但有没有更好的方法来访问列表中的值?
然后我尝试用字典来解析给定的字典:
dict_parser = argparse.ArgumentParser()
dict_parser.add_argument('--dict', nargs='*',type=dict,default={})
Out[104]: _StoreAction(option_strings=['--dict'], dest='dict', nargs='*', const=None, default={}, type=<type 'dict'>, choices=None, help=None, metavar=None)
arg2 = dict_parser.parse_args("--dict {'name':'man', 'address': 'kac', 'tags':'don'}")
usage: -c [-h] [--dict [DICT [DICT ...]]]
-c: error: unrecognized arguments: - - d i c t { ' n a m e ' : ' m a n' , ' a d d r e s s ' : ' k a c' , ' t a g s ' : ' d o n ' }
To exit: use 'exit', 'quit', or Ctrl-D.
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
那是行不通的。 Q2:以上对字典有什么作用?
Q3:现在我想要
python my.py --ls tomato jug andes --dict {'name':'man', 'address': 'kac', 'tags':'don'}
待解析
我该怎么做?
我提到了http://parezcoydigo.wordpress.com/2012/08/04/from-argparse-to-dictionary-in-python-2-7/
...并发现在字典下分配所有内容非常有用。有人可以简化此任务以解析参数中的多种数据类型吗?
【问题讨论】:
-
Q1:你想要什么?你得到的参数正是你提出的,包括引号。如果您不想这样,请不要用引号将参数括起来。
-
Q2:你把 Python 和 shell 搞混了。参数通常在 shell 上给出,并且不包含任何 Python 字典的概念。因此,您不能通过参数创建 Python 字典,事实上,您甚至不应该尝试。只需将每个键设为单独的选项并照此使用即可。
-
@Evert 你的意思是“--ls 番茄壶安第斯山脉”??
-
请注意,这在我看来是一种非常规的使用选项的方式。
python my.py --ls tomato jug andes --name man --address kac --tags don怎么了?
标签: python python-2.7 argparse