2

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?

4

1 回答 1

2

与(清理了一下):

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='?')

我预计

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)

如果我将参数更改为

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='?')

我期待

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

您还可以将一个参数与 一起使用nargs='*',并获取一个整数列表,namespace=[32, 34]然后您可以将其拆分为lengthwidth

于 2015-12-14T23:52:10.000 回答