Setting options from environment variables when using argparse
You can set the default=
of the argument to a .get()
of os.environ
with the environment variable you want to grab.
You can also pass a 2nd argument in the .get()
call, which is the default value if .get()
doesn't find an environment variable by that name (by default .get()
returns None
in that case).
import argparse
import os
parser = argparse.ArgumentParser(description='test')
parser.add_argument('--url', default=os.environ.get('URL'))
args = parser.parse_args()
if not args.url:
exit(parser.print_usage())
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()