问题
this is a question about argparse in python, it is probably very easy
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). so that i can directly check the value of lib not by specifying name of the module at the front
PS: i have a lot of variables, i do not want to reassign every single one
回答1:
First, I'm going to recommend using the args specifier. It makes it very clear where lib is coming from. 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. I wouldn't consider saving a few instances of args. to be a good enough reason. That said, here it is:
globals().update(args.__dict__)
回答2:
Sure, just add a line which assigns args.lib to lib.
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-lib')
args = parser.parse_known_args()
lib = args.lib
if lib == 'lib':
print 'aa'
回答3:
of coarse ... but just be cause you can doesnt mean you should ... but just for kicks globals().update(dict(args._get_kwargs()))
来源:https://stackoverflow.com/questions/24127388/python-argparse-how-to-refer-args-by-their-name