简体   繁体   English

python argparse,如何通过名称引用args

[英]python argparse, how to refer args by their name

this is a question about argparse in python, it is probably very easy 这是一个关于arthon中的argparse的问题,它可能很容易

import argparse

parser=argparse.ArgumentParser()

parser.add_argument('--lib')

args = parser.parse_known_args()

if args.lib == 'lib':
    print 'aa'

this would work, but instead of calling args.lib, i only want to say 'lib' (i dont want to type more), is there a way to export all the args variable out of the module (ie changing scope). 这会工作,但不是调用args.lib,我只想说'lib'(我不想输入更多),有没有办法将所有args变量导出模块(即更改范围)。 so that i can directly check the value of lib not by specifying name of the module at the front 所以我可以通过在前面指定模块的名称来直接检查lib的值

PS: i have a lot of variables, i do not want to reassign every single one PS:我有很多变数,我不想重新分配每一个变量

First, I'm going to recommend using the args specifier. 首先,我将建议使用args说明符。 It makes it very clear where lib is coming from. 它清楚地说明了lib的来源。 That said, if you find you're referring to an argument a lot, you can assign it to a shorter name: 也就是说,如果你发现你的参数很多,你可以将它分配给一个较短的名字:

lib = args.lib

There's a way to dump all the attributes into the global namespace at once, but it won't work for a function's local namespace, and using globals without a very good reason is a bad idea. 有一种方法可以同时将所有属性转储到全局命名空间中,但它不适用于函数的本地命名空间,并且没有很好的理由使用globals是一个坏主意。 I wouldn't consider saving a few instances of args. 我不会考虑保存一些args.实例args. to be a good enough reason. 是一个足够好的理由。 That said, here it is: 那就是说,这是:

globals().update(args.__dict__)

Sure, just add a line which assigns args.lib to lib . 当然,只需添加一行将args.lib分配给lib

import argparse

parser=argparse.ArgumentParser()    
parser.add_argument('-lib')    
args = parser.parse_known_args()

lib = args.lib 

if lib == 'lib':
    print 'aa'

粗略...但只是因为你不能意味着你应该...但只是为了踢全球globals().update(dict(args._get_kwargs()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM