Created
August 18, 2021 10:40
-
-
Save PatTheSilent/48b49afaa114548d5fb498157d0dc88a to your computer and use it in GitHub Desktop.
argparse action to get a default arg value from environment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# originally found in https://stackoverflow.com/a/10551190 | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment