[Python-ideas] Fwd: argparse - add support for environment variables

Chris Jerdonek chris.jerdonek at gmail.com
Wed Feb 20 09:40:57 CET 2013


On Tue, Feb 19, 2013 at 3:51 PM, Miki Tebeka <miki.tebeka at gmail.com> wrote:
>
>> Why not:
>>
>>     parser.add_argument('--spam', default=os.environ.get('SPAM', 7))
>
>  Mainly because then you can't swap in different dictionaries to resolve
> SPAM (when specifying "env" to ArgumentParser).

Couldn't you achieve this with a simple helper function?  Something
along the lines of--

env = {'SPAM': 9}
parser = argparse.ArgumentParser()
def add_argument(key, *args, **kwargs):
    if key in env:
        kwargs['default'] = env[key]
    parser.add_argument(*args, **kwargs)
add_argument('SPAM', '--spam', default=7)
...

This also allows env to be an arbitrary dictionary.

--Chris



More information about the Python-ideas mailing list