Skip to content

Instantly share code, notes, and snippets.

@PatTheSilent
Created August 18, 2021 10:40
Show Gist options
  • Save PatTheSilent/48b49afaa114548d5fb498157d0dc88a to your computer and use it in GitHub Desktop.
Save PatTheSilent/48b49afaa114548d5fb498157d0dc88a to your computer and use it in GitHub Desktop.
argparse action to get a default arg value from environment
# 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