這顯然是的一個尷尬的規範,我懷疑大多數其他POSIX風格的解析器。
掃描sys.argv
並調整解析器定義是一種可能的方法。
另一種是用一個2級剖析,以parse_known_args
:
import argparse
usage = 'prog [-h] [--simulation] [arg1 arg2 arg3 arg4]'
parser1 = argparse.ArgumentParser(usage=usage)
parser1.add_argument('--simulation', action='store_true')
# or omit the `store_true` if it just takes one argument
# other possible optionals
parser2 = argparse.ArgumentParser()
#parser2.add_argument("arg1", type = bool) # not a valid type parameter
parser2.add_argument("arg2")
parser2.add_argument("arg3", type = int)
parser2.add_argument("arg4")
# positionals are required, unless nargs=? or *
args, extras = parser1.parse_known_args()
if not args.simulation:
args = parser2.parse_args(extras, namespace=args)
elif extras:
parser1.error('cannot use --simulation with args')
print(args)
可能的運行包括:
1526:~/mypy$ python stack41556997.py -h
usage: prog [-h] [--simulation] [arg1 arg2 arg3 arg4]
optional arguments:
-h, --help show this help message and exit
--simulation
1526:~/mypy$ python stack41556997.py --simulation
Namespace(simulation=True)
1527:~/mypy$ python stack41556997.py 1 2 3
Namespace(arg2='1', arg3=2, arg4='3', simulation=False)
1527:~/mypy$ python stack41556997.py 1 2 3 --sim
usage: prog [-h] [--simulation] [arg1 arg2 arg3 arg4]
stack41556997.py: error: cannot use --simulation with args
注意,幫助不包括兩套。我在自定義用法中包含了一些信息,但arg#
沒有幫助行。生成一個好的help
消息將與您的規格尷尬。
我跳過了你的arg1
。 type=bool
不是有效的type
參數。請參閱我的解釋Parsing boolean values with argparse
我將--simulation
更改爲store_true
,因爲您說它沒有任何參數。這是接受True/False的正常方式。
Subparsers通常是接受不同模式參數的最佳工具。在這種情況下,你可以有一個叫做'simulate'的subparser不需要任何參數,另一個叫'somethingelse'需要4個參數。
我打算建議一個與--simulation
和可選項互斥的組。但一個store_true
的論點不適用於這樣的組。
=============
子分析器路線:
parser = argparse.ArgumentParser()
sp = parser.add_subparsers(dest='cmd')
sp.add_parser('simulate')
parser2 = sp.add_parser('other')
parser2.add_argument("arg2")
parser2.add_argument("arg3", type = int)
parser2.add_argument("arg4")
print(parser.parse_args())
測試:
1552:~/mypy$ python stack41556997.py -h
usage: stack41556997.py [-h] {simulate,other} ...
positional arguments:
{simulate,other}
optional arguments:
-h, --help show this help message and exit
1557:~/mypy$ python stack41556997.py simulate
Namespace(cmd='simulate')
1557:~/mypy$ python stack41556997.py other -h
usage: stack41556997.py other [-h] arg2 arg3 arg4
positional arguments:
arg2
arg3
arg4
optional arguments:
-h, --help show this help message and exit
1557:~/mypy$ python stack41556997.py other 1 2 3
Namespace(arg2='1', arg3=2, arg4='3', cmd='other')
注意,arg3
type
轉換的輸入到一個整數。其他人留作字符串。有了這個設置,args.cmd
將成爲子分析器的名稱,與布爾型args.simulation
屬性不完全相同。
==================
甲標記默認參數不要求的。位置參數是必需的,除非nargs
值爲'?'要麼 '*'。您無法爲位置提供「必需」參數。
你使用'type = bool'是有問題的。請參閱我答案中的鏈接。 – hpaulj