Multiple positional arguments with Python and argparse

后端 未结 4 1697
梦毁少年i
梦毁少年i 2021-02-01 14:53

I\'m trying to use argparse to parse the command line arguments for a program I\'m working on. Essentially, I need to support multiple positional arguments spread within the opt

4条回答
  •  盖世英雄少女心
    2021-02-01 15:25

    The 'append' action makes more sense with an optional:

    parser.add_argument('-i', '--input',action='append')
    parser.parse_args(['-i','fileone', '-a', '-i','filetwo', '-b', '-i','filethree'])
    

    You can interleave optionals with separate positionals ('input1 -a input2 -b input3'), but you cannot interleave optionals within one multiitem positional. But you can accomplish this with a two step parse.

    import argparse
    parser1 = argparse.ArgumentParser()
    parser1.add_argument('-a', action='store_true')
    parser1.add_argument('-b', action='store_true')
    parser2 = argparse.ArgumentParser()
    parser2.add_argument('input', nargs='*')
    
    ns, rest = parser1.parse_known_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])
    # Namespace(a=True, b=True), ['fileone', 'filetwo', 'filethree']
    
    ns = parser2.parse_args(rest, ns)
    # Namespace(a=True, b=True, input=['fileone', 'filetwo', 'filethree'])
    

    http://bugs.python.org/issue14191 is a proposed patch that will do this with single call to:

    parser.parse_intermixed_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])
    

提交回复
热议问题