Arbitrary command line arguments in python

前端 未结 3 1648
离开以前
离开以前 2021-01-06 11:55

I want to allow arbitrary command line arguments. If the user provides me with a command line that looks like this

myscript.py --a valueofa --b valueofb posar

3条回答
  •  生来不讨喜
    2021-01-06 12:53

    arbitrary_args.py:

    #!/usr/bin/env python3
    
    import sys
    
    
    def parse_args_any(args):
        pos = []
        named = {}
        key = None
        for arg in args:
            if key:
                if arg.startswith('--'):
                    named[key] = True
                    key = arg[2:]
                else:
                    named[key] = arg
                    key = None
            elif arg.startswith('--'):
                key = arg[2:]
            else:
                pos.append(arg)
        if key:
            named[key] = True
        return (pos, named)
    
    
    def main(argv):
        print(parse_args_any(argv))
    
    
    if __name__ == '__main__':
        sys.exit(main(sys.argv[1:]))
    

    $./arbitrary_args.py cmd posarg1 posarg2 --foo --bar baz posarg3 --quux:

    (['cmd', 'posarg1', 'posarg2', 'posarg3'], {'foo': True, 'bar': 'baz', 'quux': True})

    argparse_arbitrary.py:

    #!/usr/bin/env python3
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-D', action='append', )
    D = {L[0]:L[1] for L in [s.split('=') for s in parser.parse_args().D]}
    print(D)
    

    $./argparse_arbitrary.py -Ddrink=coffee -Dsnack=peanut

    {'snack': 'peanut', 'drink': 'coffee'}

提交回复
热议问题