2 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
從Python 3.7開(kāi)始,似乎argparse
現(xiàn)在支持這種Unix風(fēng)格的解析:
混合解析
ArgumentParser.parse_intermixed_args(args=None, namespace=None)
許多 Unix 命令允許用戶(hù)將可選參數(shù)與位置參數(shù)混合。和
parse_intermixed_args()
方法parse_known_intermixed_args()
支持這種解析風(fēng)格。
有一個(gè)警告,但對(duì)于“簡(jiǎn)單”選項(xiàng),它不會(huì)影響它們:
這些解析器不支持所有 argparse 功能,如果使用不支持的功能,則會(huì)引發(fā)異常。特別是,
argparse.REMAINDER
不支持子解析器、 和同時(shí)包含可選值和位置值的互斥組。
(我花了 1 個(gè)小時(shí)試圖理解為什么 Pythonargparse
文檔中的示例似乎沒(méi)有包含它,然后偶然發(fā)現(xiàn)了一個(gè)有點(diǎn)不相關(guān)的問(wèn)題,其中包含對(duì)這個(gè)“混合”函數(shù)的提及一條評(píng)論,我無(wú)法再次找到正確引用它的評(píng)論。)

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超11個(gè)贊
我不熟悉 argparse 所以我會(huì)編寫(xiě)自己的代碼來(lái)處理參數(shù)。
import sys
#the first argument is the name of the program, so we skip that
args = sys.argv[1:]
#just for debugging purposes:
argsLen = len(args)
print(args, argsLen)
#Create a list that will contain all of the indeces that you will have parsed through
completedIndeces = []
i = 0
#add the index to the completed indeces list.
def goToNextIndex(j):
global i
completedIndeces.append(j)
i += 1
def main():
global i
###core logic example
#Go through each item in args and decide what to do based on the arugments passed in
for argu in args:
if i in completedIndeces:
print("breaking out")
#increment i and break out of the current loop
i += 1
# If the indeces list has the index value then nothing else is done.
pass
elif argu == "joe":
print("did work with joe")
goToNextIndex(i)
elif argu == "sam":
print("did work with sam")
goToNextIndex(i)
elif argu == "school":
print("going to school")
goToNextIndex(i)
# If the argument has other arguments after it that are associated with it
# then add those indeces also to the completed indeces list.
#take in the argument following school
nextArg = i
#Do some work with the next argument
schoolName = args[nextArg]
print(f"You're going to the school called {schoolName}")
#make sure to skip the next argument as it has already been handled
completedIndeces.append(nextArg)
else:
print(f"Error the following argument is invalid: {argu}")
goToNextIndex(i)
print(f"Value of i: {i}")
print(f"completed indeces List: {completedIndeces}")
main()
添加回答
舉報(bào)