Search code examples
pythonlistsplitoptparse

Python : resplit an optionparser list


I need to analyze all the signatures I've got in input. For example my input can be :

$ python script.py -i 4:64+0:0:1460:mss*20,7:mss,sok,ts,nop,ws:df:0

I would like to split this input at : and ,, so that I end up with a list that looks like this:

['4', '64', '0', '1460', 'mss*20', '7', 'mss', 'sok', 'ts', 'nop', 'ws', 'df', '0']

I can then do a loop or index to analyze the position of my item. My program works when I use the functions input() and re.split(). But not when i want to put my signature in arguments with optparse.

If someone can help me that would be nice, thanks for your help.


Solution

  • I think it is simple. The magic are string functions: replace and split. Function split split string with given separator to the list. But you cannot use any spaces in your parsed string, because the argparse would think it is other commandline argument.

    Here is complete code of script.py

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*
    
    import argparse
    
    DESCRIPTION=u"My parser"
    def InitParser():
        parser = argparse.ArgumentParser(DESCRIPTION)
        parser.add_argument(
            '-i', '--input', 
            help=u"Parameter splitted by comma or column"
        )
        return parser
    
    def main():
        parser = InitParser()
        args = parser.parse_args()
        print "Parser args=", args
        print
        if args.input:
            lst = args.input.replace(':',',').split(',')
            print "Splited -i argument:"
            print(lst)
        else:
            print "Missing -i argument"
            return
    
    if __name__ == "__main__":
        main()
    

    Program output:

    C:\temp\tem>script.py -i 4:64+0:0:1460:mss*20,7:mss,sok,ts,nop,ws:df:0
    Parser args= Namespace(input='4:64+0:0:1460:mss*20,7:mss,sok,ts,nop,ws:df:0')
    
    Splited -i argument:
    ['4', '64+0', '0', '1460', 'mss*20', '7', 'mss', 'sok', 'ts', 'nop', 'ws', 'df', '0']