Here are two possible ways to run a Python program with arguments
python ./main.py setup-queues
or
python ./main.py -n 2 -i 1
If the sub-command setup-queues
is not given, root arguments -n
& -i
must be provided.
On the other hand, setup-queues
must be given when the root arguments are missing.
Here is my initial code to do argument parsers
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='Hello')
num_arg = parser.add_argument("-n", "--number", type=int)
parser.add_argument("-i", "--index", type=int)
subparsers = parser.add_subparsers(help='sub-command help')
# setup queue
queue_parser = subparsers.add_parser("setup-queues")
queue_parser.set_defaults(func=setup_queue)
args = parser.parse_args()
args.func(args)
# raising error in case of number is zero
if args.number == 0:
raise argparse.ArgumentError(num_arg, f"{num_arg.dest} argument should be more than zero!")
print(f"Given parameter: n: {args.number} & i: {args.index}")
When the command line is python ./main.py setup-queues
:
I expect the code to run only setup_queue
when sub-command setup-queues
is given.
However, the code keeps running till the final line. I expect it to run only setup-queue
method & exit.
When the command line is python ./main.py -n 2 -i 1
I expect the code runs till the final line.
Is there a better way to handle sub-command & root arguments?
Another question: What is the convention to handle multiple words sub-command? Adding a dash?