Multiple positional arguments with Python and argparse

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

    You can't interleave the switches (i.e. -a and -b) with the positional arguments (i.e. fileone, filetwo and filethree) in this way. The switches must appear before or after the positional arguments, not in-between.

    Also, in order to have multiple positional arguments, you need to specify the nargs parameter to add_argument. For example:

    parser.add_argument('input', nargs='+')
    

    This tells argparse to consume one or more positional arguments and append them to a list. See the argparse documentation for more information. With this line, the code:

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

    results in:

    Namespace(a=True, b=True, input=['fileone', 'filetwo', 'filethree'])
    

提交回复
热议问题