python argparse - either both optional arguments or else neither one

后端 未结 3 1297
耶瑟儿~
耶瑟儿~ 2020-12-29 04:25

I have a program that uses a default name and password. I\'m using argparse to allow the user to specify command line options, and I would like to enable the user to provid

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 05:02

    I know this is more than two years late, but I found a nice and concise way to do it:

    if bool(ns.username) ^ bool(ns.password):
        parser.error('--username and --password must be given together')
    

    ^ is the XOR operator in Python. To require both arguments given at the command line is essentially an XOR test.

提交回复
热议问题