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

Leave a Comment