Search code examples
python-3.xargparseoptional-arguments

How to give a python program two optional command-line integer arguments?


I am helping a friend with some Python code. I am making a menu, and I would like to make the dimensions customizable. I have been playing with argparse, and I have had no luck. My idea is to have menu.py default to 80*24, and have menu.py 112 84 set to 112*84. I have my current code here:

import argparse
args = argparse.ArgumentParser(description='The menu')
width = length = 0
args.add_argument('--width', const=80, default=80, type=int,
                  help='The width of the menu.', nargs='?', required=False)
args.add_argument('--length', const=24, default-24, type=int,
                  help='The length of the menu.', nargs='?', required=False)
inpu = args.parse_args()
width = inpu.width
length = inpu.length
print(width)
print(length)

How can I do this with argparse?


Solution

  • With (cleaned up a bit):

    args.add_argument('-w','--width', const=84, default=80, type=int,
                  help='The width of the menu.', nargs='?')
    args.add_argument('-l','--length', const=28, default=24, type=int,
                  help='The length of the menu.', nargs='?')
    

    I expect

    menu.py  => namespace(length=24, width=80)
    menu.py -w -l -w => namespace(length=28, width=84)
    menu.py -w 23 -l 32 => namespace(length=32, width=23)
    

    If I change the arguments to

    args.add_argument('width', default=80, type=int,
                  help='The width of the menu.', nargs='?')
    args.add_argument('length', default=24, type=int,
                  help='The length of the menu.', nargs='?')
    

    I'd expect

    menu.py => namespace(length=24, width=80)
    menu.py 32 => namespace(length=24, width=32)
    menu.py 32 33 => namespace(length=33, width=32)
    

    You could also use one argument with nargs='*', and get a list of integers, namespace=[32, 34] that you could then split between length and width.