0

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?

hunterex
  • 565
  • 11
  • 27
  • By ordinary python syntax, once `args.func(args)`, it continues with the next line of the code. – hpaulj Aug 08 '22 at 15:52
  • @hpaulj, does that mean I need to add an if condition checking whether `-n` & `-i` are provided after `args.func(args)`, then decide whether to return or continue running the code? – hunterex Aug 08 '22 at 15:58
  • Especially when debugging, I suggest including a `print(args)` statement right after `parse_args`. That way you'll have a clearer idea of what parsing has done. You might also want to add a `dest='cmd'` to the `subparsers` command. After `parse_args`, the `argparse` part is done. The rest is up to you - ordinary python testing of values, and doing what makes most sense. You probably do want some `if/else` blocks to handle the alternatives. – hpaulj Aug 08 '22 at 18:15
  • The easiest solution would be to put an `exit 0` at the end of your `setup_queue` function. – Amos Baker Aug 08 '22 at 19:26

0 Answers0