Last active
March 17, 2018 16:55
-
-
Save adamabernathy/0f6941db98a5857dd7fa513e6646c77a to your computer and use it in GitHub Desktop.
Simple CLI arguments parser
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
'''Simple CLI arguments parser | |
Requires the `--key=value` format. Defaults to True if value is omitted. | |
(C) 2018 Adam C. Abernathy, [email protected] | |
''' | |
import sys | |
def coerce_value(value=None): | |
'''Attempts to coerce a value into either float, bool or string''' | |
if not isinstance(value, str): | |
return value | |
try: | |
return float(value) | |
except: | |
# Assume NaN, so test for boolean | |
if value.upper() in ('TRUE', 'FALSE'): | |
return True if value.upper() == 'TRUE' else False | |
else: | |
return value | |
def parse_cli(accepted_args={}, parse_all=False): | |
'''Parse CLI arguments''' | |
parse_all = True if parse_all or len(accepted_args.keys()) == 0 else False | |
for item in sys.argv: | |
try: | |
key = (item.split('--')[1]).split('=')[0] | |
_value = (item.split('--')[1]).split('=') | |
value = _value[1] if len(_value) > 1 else True | |
if parse_all: | |
accepted_args[key] = coerce_value(value) | |
elif key in accepted_args: | |
accepted_args[key] = coerce_value(value) | |
else: | |
pass | |
except IndexError: | |
pass | |
except ValueError: | |
pass | |
except: | |
print 'Error parsing CLI arguments!' | |
return None | |
return accepted_args | |
if __name__ == "__main__": | |
accepted_args = { | |
'file': None, | |
'verbose': None, | |
} | |
print parse_cli(accepted_args) | |
print parse_cli(accepted_args, True) | |
print parse_cli() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment