Created
June 19, 2020 17:48
-
-
Save nkpro2000sr/ad92840b5a0dd5aa30da70b3792497d9 to your computer and use it in GitHub Desktop.
Parse positional and optional arguments from argstr. (var length 'pos & optional arguments' based on 'shlex')
This file contains 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 re | |
import shlex | |
def _until_dh(splited): | |
""" Slice until double hyphen """ | |
i = 0 | |
for i, s in enumerate(splited): | |
if s == "--": | |
return splited[:i], i+1 | |
elif s.startswith("--"): | |
return splited[:i], i | |
return splited[:], i+1 | |
def shlex_argparse(argstr): | |
""" Get positional arguments and optional arguments from argstr. | |
Example:: | |
parse p1 p2 'p3 three' --o1=one '--o2=two' --o3='3 three' p'4 four' --o4 four Four | |
as args = ['p1', 'p2', 'p3 three', 'p4 four'] | |
and kwargs = {'o1':'one', 'o2':'two', 'o3':'3 three', 'o4':['four', 'Four']} | |
""" | |
args = shlex.split(argstr) | |
classify = re.compile(r"^(?:(?:--(\w+)=([\s\S]*))|(?:--(\w+))|(\S[\s\S]*))$") | |
positional_args = [] | |
optional_args = {} | |
i = 0 | |
while i < len(args): | |
match = classify.match(args[i]) | |
if match is None: | |
raise re.error("Not matched", pattern=classify) | |
key, value, var_key, pos = match.groups() | |
if pos: | |
if pos != "--": | |
positional_args.append(pos) | |
elif key: | |
optional_args[key] = value | |
elif var_key: | |
optional_args[var_key], j = _until_dh(args[i+1:]) | |
i += j | |
i += 1 | |
return positional_args, optional_args |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment