使用 argparse 时从环境变量设置选项 [英] Setting options from environment variables when using argparse

查看:40
本文介绍了使用 argparse 时从环境变量设置选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,其中包含可以在命令行或环境变量中传递的某些选项.如果两者都存在,CLI 应该优先,如果两者都没有设置,则会发生错误.

I have a script which has certain options that can either be passed on the command line, or from environment variables. The CLI should take precedence if both are present, and an error occur if neither are set.

我可以在解析后检查该选项是否已分配,但我更喜欢让 argparse 来完成繁重的工作,并在解析失败时负责显示使用说明.

I could check that the option is assigned after parsing, but I prefer to let argparse to do the heavy lifting and be responsible for displaying the usage statement if parsing fails.

我为此提出了几种替代方法(我将在下面将其作为答案发布,以便可以单独讨论),但我觉得它们很笨拙,我认为我遗漏了一些东西.

I have come up with a couple of alternative approaches to this (which I will post below as answers so they can be discussed separately) but they feel pretty kludgey to me and I think that I am missing something.

是否有公认的最佳"方法?

Is there an accepted "best" way of doing this?

(当 CLI 选项和环境变量都未设置时,编辑以明确所需的行为)

(Edit to make the desired behaviour clear when both the CLI option and environment variable are unset)

推荐答案

我经常使用这种模式,以至于我打包了一个简单的操作类来处理它:

I use this pattern frequently enough that I have packaged a simple action class to handle it:

import argparse
import os

class EnvDefault(argparse.Action):
    def __init__(self, envvar, required=True, default=None, **kwargs):
        if not default and envvar:
            if envvar in os.environ:
                default = os.environ[envvar]
        if required and default:
            required = False
        super(EnvDefault, self).__init__(default=default, required=required, 
                                         **kwargs)

    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, values)

然后我可以从我的代码中调用它:

I can then call this from my code with:

import argparse
from envdefault import EnvDefault

parser=argparse.ArgumentParser()
parser.add_argument(
    "-u", "--url", action=EnvDefault, envvar='URL', 
    help="Specify the URL to process (can also be specified using URL environment variable)")
args=parser.parse_args()

这篇关于使用 argparse 时从环境变量设置选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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