Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse Args that aren't declared

Tags:

python

I'm writing a utility for running bash commands that essentially takes as input a string and a list optional argument and uses the optional arguments to interpolate string.

I'd like it to work like this:

interpolate.py Hello {user_arg} my name is {computer_arg} %% --user_arg=john --computer_arg=hal

The %% is a separator, it separates the string to be interpolated from the arguments. What follows is the arguments used to interpolate the string. In this case the user has chosen user_arg and computer_arg as arguments. The program can't know in advance which argument names the user will choose.

My problem is how to parse the arguments? I can trivially split the input arguments on the separator but I can't figure out how to get optparse to just give the list of optional args as a dictionary, without specifying them in advance. Does anyone know how to do this without writing a lot of regex?

like image 399
user683264 Avatar asked Dec 30 '25 22:12

user683264


1 Answers

Well, if you use '--' to separate options from arguments instead of %%, optparse/argparse will just give you the arguments as a plain list (treating them as positional arguments instead of switched). After that it's not 'a lot of' regex, it's just a mere split:

for argument in args:
    if not argument.startswith("--"):
        # decide what to do in this case...
        continue
    arg_name, arg_value = argument.split("=", 1)
    arg_name = arg_name[2:]
    # use the argument any way you like
like image 192
vmalloc Avatar answered Jan 02 '26 13:01

vmalloc