Difference between revisions of "Argparse set from env var"

From UVOO Tech Wiki
Jump to navigation Jump to search
 
Line 3: Line 3:
  
 
https://gist.github.com/orls/51525c86ee77a56ad396
 
https://gist.github.com/orls/51525c86ee77a56ad396
 +
 +
 +
# Example 1
 +
```
 +
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)
 +
```
 +
 +
```
 +
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()
 +
```
 +
 +
 +
# Another Example
 +
```
 +
import argparse
 +
import os
 +
 +
# Courtesy of http://stackoverflow.com/a/10551190 with env-var retrieval fixed
 +
class EnvDefault(argparse.Action):
 +
    """An argparse action class that auto-sets missing default values from env
 +
    vars. Defaults to requiring the argument."""
 +
 +
    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)
 +
 +
# functional sugar for the above
 +
def env_default(envvar):
 +
    def wrapper(**kwargs):
 +
        return EnvDefault(envvar, **kwargs)
 +
    return wrapper
 +
```
 +
 +
```
 +
import argparse
 +
 +
from EnvDefault import env_default
 +
 +
 +
if __name__ == "__main__":
 +
 +
    parser = argparse.ArgumentParser(
 +
        description="use env vars as defaults for argparse"
 +
    )
 +
 +
    parser.add_argument(
 +
        "--alpha", "-a",
 +
        action=env_default('ALPHA'),
 +
        required=False,
 +
        help="""Optional. Value from CLI will be used if present, or from env var ALPHA.
 +
If neither of these is present, value is None becasue no fallback default
 +
was given"""
 +
    )
 +
 +
    parser.add_argument(
 +
        "--beta", "-b",
 +
        action=env_default('BETA'),
 +
        required=True,
 +
        help="""Required. Value from CLI will be used if present, or from env var BETA.
 +
If neither of these is present, it's an error"""
 +
    )
 +
 +
    parser.add_argument(
 +
        "--gamma", "-g",
 +
        action=env_default('GAMMA'),
 +
        required=True,
 +
        default=9001,
 +
        help="""Value from CLI will be used if present, or from env var GAMMA.
 +
If neither of these is present, default of 9001 is used"""
 +
    )
 +
 +
    print parser.parse_args()
 +
```

Latest revision as of 15:33, 8 April 2023

https://stackoverflow.com/questions/10551117/setting-options-from-environment-variables-when-using-argparse

https://gist.github.com/orls/51525c86ee77a56ad396

Example 1

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

Another Example

import argparse
import os

# Courtesy of http://stackoverflow.com/a/10551190 with env-var retrieval fixed
class EnvDefault(argparse.Action):
    """An argparse action class that auto-sets missing default values from env
    vars. Defaults to requiring the argument."""

    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)

# functional sugar for the above
def env_default(envvar):
    def wrapper(**kwargs):
        return EnvDefault(envvar, **kwargs)
    return wrapper
import argparse

from EnvDefault import env_default


if __name__ == "__main__":

    parser = argparse.ArgumentParser(
        description="use env vars as defaults for argparse"
    )

    parser.add_argument(
        "--alpha", "-a",
        action=env_default('ALPHA'),
        required=False,
        help="""Optional. Value from CLI will be used if present, or from env var ALPHA.
If neither of these is present, value is None becasue no fallback default
was given"""
    )

    parser.add_argument(
        "--beta", "-b",
        action=env_default('BETA'),
        required=True,
        help="""Required. Value from CLI will be used if present, or from env var BETA.
If neither of these is present, it's an error"""
    )

    parser.add_argument(
        "--gamma", "-g",
        action=env_default('GAMMA'),
        required=True,
        default=9001,
        help="""Value from CLI will be used if present, or from env var GAMMA.
If neither of these is present, default of 9001 is used"""
    )

    print parser.parse_args()