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

查看:25
本文介绍了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'

这行得通,但我不想调用 args.lib,我只想说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天全站免登陆