簡體   English   中英

如何將 *args 與 argparse 一起使用?

[英]How to use *args with argparse?

我正在嘗試使用 argparse 模塊來解析命令行 arguments,並且我想使用 *args 因為 arguments 的數量不固定。

我的代碼:

if __name__ == '__main__':
    
    parser = argparse.ArgumentParser()
    parser.add_argument("program", help='Name of the program')
    parser.add_argument("type", help='Type of program')
    parser.add_argument("date", help='Date of the file')

這 3 個 arguments 是必須的:程序、類型和日期。 但是,下一個 arguments 是可選的(有時需要,有時不需要)。 所以,我想為其他 arguments 使用 *args,但我不確定使用 argsparse 是如何完成的。

可選的 arguments 如下所示:

if __name__ == '__main__':
    
    parser = argparse.ArgumentParser()
    parser.add_argument("program", help='Name of the program')
    parser.add_argument("type", help='Type of program')
    parser.add_argument("date", help='Date of the file')

    #below arguments are optinal. Hence, I may need to pass all of them in one scenario, or just 1-2 in 
    another scenario.

    parser.add_argument("option1", help='optinal 1')
    parser.add_argument("option2", help='optinal 2')
    parser.add_argument("option3", help='optinal 3')
    parser.add_argument("option4", help='optinal 4')

請幫忙。 提前致謝。

https://docs.python.org/3/library/argparse.html#the-add-argument-method

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

name of flags是一個*args參數; 您可以為positional指定單個名稱或為optional指定多個名稱(例如 `('-f','--foo', '--foobar',...)

其他 arguments 以**kwargs的形式接收,因此通常像使用help參數一樣提供。

由於有很多可能的參數,我建議從最簡單的開始,然后進行實驗。

最重要的是https://docs.python.org/3/library/argparse.html#name-or-flags 其次是https://docs.python.org/3/library/argparse.html#nargs

使用關鍵字required=bool

parser = argparse.ArgumentParser()
parser.add_argument("-p","--program", help='Name of the program', required=True)
parser.add_argument("-f", "--foo", help='Foo', required=False)

暫無
暫無

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

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