Last active
July 27, 2020 18:38
-
-
Save tomvit/06afcd569a6bbf194aaea4475b06fb5e to your computer and use it in GitHub Desktop.
Simple argument parser that works in Jython
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
import sys | |
import re | |
def parse_args(args_def): | |
""" | |
Simple argument parser. args_def is a dict in the following format. | |
The multi property can be used to parse comma separated values. | |
args_def = { | |
"user" : { "required": False, "default": "weblogic" }, | |
"password" : { "required": True }, | |
"command" : { "required": True, "validation": r"start|shutdown" }, | |
"server_names": { "required": True, "multi": True }, | |
"rolling" : { "required": False, "default": False, "type": bool } | |
} | |
""" | |
i = 1; args = {}; add_next = False; prev_key = None | |
# parse arguments | |
while i < len(sys.argv): | |
key = sys.argv[i] | |
arg_def = args_def.get(key[1:], None) | |
if key[0] == "-" and arg_def: | |
value = sys.argv[i + 1] | |
if arg_def.get("type", str) == bool: | |
if value not in ["True", "False", "true", "false"]: | |
raise Exception("Argument " + key + " has invalid boolean value: " + value) | |
value = value in ["True", "true"] | |
add_next = arg_def.get("multi", False) | |
if not add_next: | |
args[key[1:]] = value | |
else: | |
# "multi" arguments' value must be a list | |
args[key[1:]] = [value] | |
prev_key = key[1:] | |
i += 2 | |
else: | |
if add_next: | |
args[prev_key].append(sys.argv[i]) | |
i += 1 | |
else: | |
raise Exception("Invalid command line argument: " + \ | |
key + ". The valid arguments are " + str(args_def)) | |
# check all required args are present, set the defaults | |
for key in args_def.keys(): | |
value = args_def[key] | |
if not args.get(key): | |
if value.get("required", False): | |
raise Exception("The command line argument " + key + " is required!") | |
if value.get("default", None): | |
args[key] = value["default"] | |
if value.get("validation") and not(re.match(value.get("validation"), args[key])): | |
raise Exception("The command line argument " + key + " has an invalid value " + args[key] + ". " + \ | |
"The validation pattern is: " + value.get("validation")) | |
return args |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment