I have a requirement as follows:
./xyifier --prox --lport lport --rport rport
for the argument prox , I use action="store_true" to check if it is present or not. I do not require any of the arguments. But, if --prox is set I require rport and lport as well. Is there an easy way of doing this with argparse without writing custom conditional coding.
non_int.add_argument("--prox", action="store_true", help="Flag to turn on proxy") non_int.add_argument("--lport", type=int, help="Listen Port.") non_int.add_argument("--rport", type=int, help="Proxy port.")
No, there isn"t any option in argparse to make mutually inclusive sets of options.
The simplest way to deal with this would be:
if args.prox and (args.lport is None or args.rport is None): parser.error("--prox requires --lport and --rport.")
You"re talking about having conditionally required arguments. Like @borntyping said you could check for the error and do
parser.error(), or you could just apply a requirement related to
--prox when you add a new argument.
A simple solution for your example could be:
non_int.add_argument("--prox", action="store_true", help="Flag to turn on proxy") non_int.add_argument("--lport", required="--prox" in sys.argv, type=int) non_int.add_argument("--rport", required="--prox" in sys.argv, type=int)
required receives either
False depending on whether the user as used
--prox. This also guarantees that
-rport have an independent behavior between each other.
Target knows. Apple Computer knows, too. So do LinkedIn, Netflix, Facebook, Twitter, Expedia, national and local political campaigns, and dozens of other organizations that all generate enormous eco...
Learning to code is tremendous fun as you can get instant results, no matter how much more you have to learn. In fact, it’s such fun creating games and programs that it feels effortless once you’r...
As the title promises, this book will introduce you to one of the world’s most popular programming languages: Python. It’s aimed at beginning programmers as well as more experienced programmers wh...
A Practical Approach to Computer Algorithms Using Python® and C# Rod Stephens started out as a mathematician, but while studying at MIT, he discovered how much fun algorithms are. He took every al...