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

前端 未结 3 2010
暗喜
暗喜 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 04:03

    Try to use the "nargs" parameter of the add_argument methode. This way it works for me. Now you can add the username twice, so you have to check it and raise an error, if you want.

    import argparse
    if __name__ == '__main__':
       parser = argparse.ArgumentParser()
       parser.add_argument("-u", "--user-name", default="admin")
       parser.add_argument("user_name", default="admin", nargs="?")
       args = parser.parse_args()
       print(args)
    

提交回复
热议问题