Pythonでは、コマンドラインオプションに無制限の数の引数を指定する方法はありますか?たとえば、のようなものpython myscript.py --use-files a b c d e
。コマンドラインオプションを厳密に使用したいことに注意してください。python myscript.py a b c d e
1 に答える
4
コマンドラインオプションは、stdlibargparseモジュールを使用すると簡単です。を使用nargs="*"
すると、オプションに任意の数の引数を指定できます。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--use-files', nargs='*', default=['a', 'b'])
args = parser.parse_args()
print(args)
出力:
$ python /tmp/spam.py
Namespace(use_files=['a', 'b'])
$ python /tmp/spam.py --use-files hello world
Namespace(use_files=['hello', 'world'])
$ 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'])
于 2012-10-11T07:23:55.940 に答える