私のアプリケーションは特殊なファイル比較ユーティリティであり、明らかに 1 つのファイルのみを比較するのは意味がないため、あまりnargs='+'
適切ではありません。
nargs=N
最大数のN
引数を除いているだけですが、少なくとも 2 つの引数がある限り、無限の数の引数を受け入れる必要があります。
簡単に言えば、nargs は「2+」などをサポートしていないため、それを行うことはできません。
長い答えは、次のようなものを使用して回避できることです。
parser = argparse.ArgumentParser(usage='%(prog)s [-h] file file [file ...]')
parser.add_argument('file1', nargs=1, metavar='file')
parser.add_argument('file2', nargs='+', metavar='file', help=argparse.SUPPRESS)
namespace = parser.parse_args()
namespace.file = namespace.file1 + namespace.file2
必要なトリックは次のとおりです。
usage
独自の使用文字列をパーサーに提供するために使用しますmetavar
ヘルプ文字列に別の名前の引数を表示するために使用しますSUPPRESS
変数の 1 つのヘルプを表示しないようにするために使用します。Namespace
パーサーが返すオブジェクトに新しい属性を追加するだけで、2 つの異なる変数をマージします。上記の例では、次のヘルプ文字列が生成されます。
usage: test.py [-h] file file [file ...]
positional arguments:
file
optional arguments:
-h, --help show this help message and exit
2つ未満の引数が渡された場合でも失敗します:
$ python test.py arg
usage: test.py [-h] file file [file ...]
test.py: error: too few arguments
次のようなことはできませんでした:
import argparse
parser = argparse.ArgumentParser(description = "Compare files")
parser.add_argument('first', help="the first file")
parser.add_argument('other', nargs='+', help="the other files")
args = parser.parse_args()
print args
これを実行すると、次の-h
ようになります。
usage: script.py [-h] first other [other ...]
Compare files
positional arguments:
first the first file
other the other files
optional arguments:
-h, --help show this help message and exit
引数を 1 つだけ指定して実行すると、機能しません。
usage: script.py [-h] first other [other ...]
script.py: error: too few arguments
ただし、2 つ以上の引数は問題ありません。3 つの引数を指定すると、次のように表示されます。
Namespace(first='one', other=['two', 'three'])