pythonprintingparametersargv

Python List to string manipulation. Print each command line argv "--option argument1 argument2" on their own separate lines


I have a working solution, it's just so gross. I often write stuff like this and then just look at it disgusted, but this one is far to gross to leave as is... especially as it's just list to string manipulation. I'm embarrassed. I'm interested in more succinct solutions. Anyone have a cleaner way to put each option parameter followed by its arguments printed on separate lines?

Input: python3 -O myscript.py --dates "2024-04-30" "2024-04-29" "2024-04-28" "2024-04-27" --names "johnson" "woody" "richard" "willy" -o "/home/stamos/pickle/pics/name_brainstorming"

sys.argv[1:] = parameter_set
print("\nGenerating parameter set: ")
parameter_set_string = ""
first_iter = True
for each in parameter_set:
    if each[0] == "-" and first_iter == False:
        print(parameter_set_string)
        parameter_set_string = each
    else: 
        if first_iter:
            parameter_set_string += each
            first_iter = False
        else:
           parameter_set_string += ' "' + each + '" '
print(parameter_set_string)

Output:

Generating parameter set:
--dates "2024-04-30" "2024-04-29" "2024-04-28" "2024-04-27"
--names "johnson" "woody" "richard" "willy" 
-o "/home/stamos/pickle/pics/name_brainstorming"

Generating parameter set:
--dates "2024-04-26" "2024-04-25" "2024-04-24"
--names "anaconda" "black mamba" "python" 
-o "/home/stamos/pickle/pics/name_brainstorming"

Solution

  • If I understood your question correctly, the following solution is a bit naive, as it assumes there are no substrings ' -' (space followed by hyphen) within the arguments themselves.

    string = 'python3 -O myscript.py --dates "2024-04-30" "2024-04-29" "2024-04-28" "2024-04-27" --names "johnson" "woody" "richard" "willy" -o "/home/stamos/pickle/pics/name_brainstorming"'
    
    args = ['-' + arg for arg in string.split(' -')[2:]]
    print(*args, sep="\n")
    

    Output:

    --dates "2024-04-30" "2024-04-29" "2024-04-28" "2024-04-27"
    --names "johnson" "woody" "richard" "willy"
    -o "/home/stamos/pickle/pics/name_brainstorming"
    

    Also not a huge fan of splitting, removing the delimiter only to be forced to add part of the delimiter back in just to print it. I would say if your arguments don't get more complex than this, this should be fine, otherwise I'd recommend a regex.