Search code examples
pythonpython-3.xdelimiter

Parsing arguments as single line or using a specified delimiter in Python


I want to parse the command line arguments while attempting to call the program in the following manner:

python plot.py --w --Develop origin plot --+3.5

I have been using sys.argv to parse them using a for loop:

for arg in sys,argv:
    print(arg)

Output:

plot.py
--w
--Developoriginplot
--+3.5

But I wish to get the output as follows:

plot.py
w
Develop origin plot
+3.5

Is there a way to split the line by specifying the delimeter -- ?


Solution

  • " ".join() the args first, then split by --.

    import sys
    
    args = " ".join(sys.argv) # join by spaces
    args = [a.strip() for a in args.split("--")] # split by --, remove any extra spaces
    print(args)
    print("\n".join(args))
    

    Output:

    $ python plot.py --w --Develop origin plot --+3.5
    ['plot.py', 'w', 'Develop origin plot', '+3.5']
    plot.py
    w
    Develop origin plot
    +3.5