Skip to content

Instantly share code, notes, and snippets.

@cbitterfield
Created January 22, 2020 04:18
Show Gist options
  • Save cbitterfield/83ef13f1ff38567cbe595c52c618eedb to your computer and use it in GitHub Desktop.
Save cbitterfield/83ef13f1ff38567cbe595c52c618eedb to your computer and use it in GitHub Desktop.
Set Environment variables for ArgParse in Python
#!/usr/bin/env python3
"""
Example CLI with using envirnment variables.
"""
# I wiill put this together as a class later.
def getenviron(prefix, **kwargs):
'''
Get a list of environment variables and return a list for ARG Parsing overrides
'''
return_list = list()
key=""
value=""
# KWARGS is a translation table KEY=Envionment Variable, Value is return key
# If set scan for this list, if not use a prefix. If prefix is set, variables are limited to the prefix
for evar in os.environ:
if prefix or evar in kwargs.keys():
value = os.environ.get(evar)
# Something we can work with
if kwargs and not prefix:
print('Kargs Only',evar)
key=kwargs.get(evar,None)
print(key,value)
elif evar.startswith(prefix) and not kwargs:
key="--" + evar.replace(prefix,'').replace('_','-').lower()
elif evar.startswith(prefix) and kwargs:
key = kwargs[evar.replace(prefix,'')]
if key:
return_list.append(key)
if value != 'True' and value != 'False' and value != 'None':
return_list.append(value)
else:
# ENV var we don't need
pass
return return_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment