python argparse, how to refer args by their name

纵饮孤独 提交于 2019-12-02 06:50:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!