Multiple positional arguments with Python and argparse

后端 未结 4 1702
梦毁少年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:24

    It seems to me that hpaulj is on the right track but making things a bit more complicated than necessary. I suspect that Blair is looking for something akin to the behavior of the old optparse module and doesn't really need the list of input arguments in the inputs field of the args object. He just wants

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', action='store_true')
    parser.add_argument('-b', action='store_true')
    opts, args = parser.parse_known_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])
    # Namespace(a=True, b=True), ['fileone', 'filetwo', 'filethree']
    

    In the vernacular of optparse, the "options" are available in opts, and the list of possibly interspersed other "arguments" are in args.

提交回复
热议问题