簡體   English   中英

為commanline選項指定無限數量的參數

[英]Specifying an unlimited number of arguments to a commanline option

在Python中,有沒有辦法為命令行選項指定無限數量的參數? 例如像python myscript.py --use-files abcde 請注意,我嚴格要使用命令行選項,例如我不只是想要python myscript.py abcde

是的,使用argparse模塊很簡單。

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--use-files', nargs='*', default=['a', 'b', 'c'], help='HI!')
args = parser.parse_args()
print args

輸出:

wim@wim-zenbook:~$ python /tmp/spam.py 
Namespace(use_files=['a', 'b', 'c'])
wim@wim-zenbook:~$ python /tmp/spam.py --use-files hello world
Namespace(use_files=['hello', 'world'])
wim@wim-zenbook:~$ python /tmp/spam.py --use-files aleph-null bottles of beer on the wall, aleph-null bottles of beer, take one down pass it around, aleph-null bottles of beer on the wall
Namespace(use_files=['aleph-null', 'bottles', 'of', 'beer', 'on', 'the', 'wall,', 'aleph-null', 'bottles', 'of', 'beer,', 'take', 'one', 'down', 'pass', 'it', 'around,', 'aleph-null', 'bottles', 'of', 'beer', 'on', 'the', 'wall'])

暫無
暫無

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

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