python argparse,如何通过其名称引用args [英] python argparse, how to refer args by their name

查看:68
本文介绍了python argparse,如何通过其名称引用args的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于python中的argparse的问题,可能很容易

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'

这可以工作,但是我只想说'lib'(我不想输入更多),而不是调用args.lib,有没有办法将所有args变量导出到模块之外(即更改范围) ).这样我就可以直接检查lib的值,而不必在前面指定模块的名称

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:我有很多变量,我不想重新分配每个变量

PS: i have a lot of variables, i do not want to reassign every single one

推荐答案

首先,我将建议使用args说明符.很清楚lib的来源.就是说,如果您发现自己经常引用某个参数,则可以将其分配给一个较短的名称:

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

有一种方法可以将所有属性立即转储到全局名称空间中,但不适用于函数的本地名称空间,并且在没有充分理由的情况下使用globals是个坏主意.我不会考虑保存几个args.实例是足够好的理由.就是说,这里是:

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__)

这篇关于python argparse,如何通过其名称引用args的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆