在Python中,有没有办法为命令行选项指定无限数量的参数?例如python myscript.py --use-files a b c d e
之类的东西。请注意,我严格要使用命令行选项,例如我不想要python myscript.py a b c d e
答案 0 :(得分:4)
是的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'])