簡體   English   中英

Argparse:如何接受具有不同“類型”的參數

[英]Argparse: How to accept arguments that have different “types”

我想接受以下樣式的參數:

python3 test.py -r SERVICE=100,101,102 -r SERVICE2=1,2,3,4,5 
(-r REPO=REV#,REV#,etc... -r etc...)

到目前為止,我已完成以下操作(添加了參數-r並定義了類型轉速)。 它應該傳回兩個列表,這可能會有問題。

import argparse

def revs(s):
    try:            
        REPO, REVISIONS = map(str, s.split('='))
        REVISIONS = map(int, REVISIONS.split(','))
        return REPO, REVISIONS
    except:
        raise argparse.ArgumentTypeError("Must be format -r REPO=REV,REV,etc.. e.g. SERVICES=181449,181447") 

parser.add_argument('-r', type='revs', nargs='*', action='append', help='Revisions to update. The list is prefixed with the name of the source repository and a "=" sign. This parameter can be used multiple times.', required=True)

運行上述內容時出現以下錯誤:

Traceback (most recent call last):
File "test.py", line 11, in <module>
parser.add_argument('-r', type='revs', nargs='*', action='append', help='Revisions to update. The list is prefixed with the name of the source repository and a "=" sign. This parameter can be used multiple times.', required=True)
File "/usr/local/lib/python3.3/argparse.py", line 1317, in add_argument
raise ValueError('%r is not callable' % (type_func,))

ValueError:'revs'不可調用

你要

parser.add_argument('-r', type=revs, ...)

parser.add_argument('-r', type='revs', ...)

type參數必須是可調用對象 - 因為字符串不可調用,所以它們不能用作type

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM