Created
January 22, 2020 04:18
-
-
Save cbitterfield/83ef13f1ff38567cbe595c52c618eedb to your computer and use it in GitHub Desktop.
Set Environment variables for ArgParse in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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