I am trying to find the most Pythonic way to take a line containing command line options:
"-t 500 -x -c 3 -d"
And turn it into a dictionary
{"-t":"500", "-x":True, "-c":"3", "-d": True}
UPDATE The line should also contain - long parameters and words with a dash in the middle:
"-t 500 -x -c 3 -d --long-option 456 -testing weird-behaviour"
Before suggesting that I look into the OptionParse module, keep in mind that I donβt know what the actual parameters are or something like that, Iβm just trying to put a string in a dictionary to allow it to change based on another options dictionary.
The approach I'm considering is to use split () to get the items in the list, and then go through the list and look for items starting with a dash β-β, and use them as a key, and then somehow get to the next item in the list for value. I have problems with parameters that do not have values. I was thinking of doing something like:
for i in range(0, len(opt_list)): if opt_list[i][0] == "-": if len(opt_list) > i+1 and not opt_list[i+1][0] == "-": opt_dict[opt_list[i]] = opt_list[i+1] else: opt_dict[opt_list[i]] = True
But it seems to me that I am programming in C not Python when I do this ...
source share