Python argparse: command-line argument that can be either named or positional

前端 未结 3 2062
暗喜
暗喜 2021-01-02 03:20

I am trying to make a Python program that uses the argparse module to parse command-line options.

I want to make an optional argument that can either be

3条回答
  •  情歌与酒
    2021-01-02 03:48

    The way the ArgumentParser works, it always checks for any trailing positional arguments after it has parsed the optional arguments. So if you have a positional argument with the same name as an optional argument, and it doesn't appear anywhere on the command line, it's guaranteed to override the optional argument (either with its default value or None).

    Frankly this seems like a bug to me, at least when used in a mutually exclusive group, since if you had specified the parameter explicitly it would have been an error.

    That said, my suggested solution, is to give the postional argument a different name.

    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-u','--username')
    group.add_argument('static_username',nargs='?',default='admin')
    

    Then when parsing, you use the optional username if present, otherwise fallback to the positional static_username.

    results = parser.parse_args()
    username = results.username or results.static_username
    

    I realise this isn't a particularly neat solution, but I don't think any of the answers will be.

提交回复
热议问题