2015-12-14 32 views
0

我正在幫助朋友使用一些Python代碼。我正在製作一個菜單,並且我想讓這些尺寸可定製。我一直在玩argparse,而且我沒有運氣。我的想法是將menu.py 默認爲80 * 24,並將menu.py 112 84設置爲112 * 84。我有我現在的代碼:如何給python程序兩個可選的命令行整數參數?

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) 

我該怎麼做​​?

+0

_「在StackOverflow上的代碼縮進不起作用」_ - 爲了將來的參考,這裏是StackOverflow的降價參考:http://stackoverflow.com/editing-help#code –

+1

@SimonMᶜKenzie預覽沒有顯示格式化我的方式認爲它應該。縮進並未在預覽中格式化。 – JackMacWindows

回答

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之間劃分。