在我们深入讨论这个问题之前,让我们先澄清一下。args=parser.parse_args()
是相同的args=parser.parse_args(sys.argv[1:])
。但我可以想象你想知道什么的情况sys.argv[1:]
会产生一些任意的args
。也许是为了测试,也许是为了驱动别人的代码。
里面没有任何代码argparse
就是这样做的。但对于有限的情况,您可以从定义的操作中获取信息,并创建一个合理的sys.argv
.
In [432]: parser = argparse.ArgumentParser()
In [433]: parser.add_argument('--example', type=int, default=0)
Out[433]: _StoreAction(option_strings=['--example'], dest='example', nargs=None, const=None, default=0, type=<type 'int'>, choices=None, help=None, metavar=None)
已定义操作的列表:
In [435]: parser._actions
Out[435]:
[_HelpAction(option_strings=['-h', '--help'], dest='help', nargs=0, const=None, default='==SUPPRESS==', type=None, choices=None, help='show this help message and exit', metavar=None),
_StoreAction(option_strings=['--example'], dest='example', nargs=None, const=None, default=0, type=<type 'int'>, choices=None, help=None, metavar=None)]
选择感兴趣的一个,然后查看它的一些属性:
In [436]: a1=parser._actions[-1]
In [437]: a1.type
Out[437]: int
In [438]: a1.default
Out[438]: 0
现在生成args
:
In [439]: args=parser.parse_args(['--example','1'])
In [440]: args
Out[440]: Namespace(example=1)
In [441]: args.example *= 2
使用 new 创建列表的简单示例args
以及来自行动的信息。显然,工作代码需要推断出要使用哪个操作。对于最常见的类型str()
足够。
In [442]: if args.example != a1.default:
.....: print(['--example',str(args.example)])
.....:
['--example', '2']
或者我可以玩metavar
属性,以及usage
格式化程序:
In [445]: a1.metavar=str(args.example)
In [446]: parser.print_usage()
usage: ipython2.7 [-h] [--example 2]