6

私のアプリケーションは特殊なファイル比較ユーティリティであり、明らかに 1 つのファイルのみを比較するのは意味がないため、あまりnargs='+'適切ではありません。

nargs=N最大数のN引数を除いているだけですが、少なくとも 2 つの引数がある限り、無限の数の引数を受け入れる必要があります。

4

2 に答える 2

18

簡単に言えば、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
于 2011-12-07T06:46:21.383 に答える
6

次のようなことはできませんでした:

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'])
于 2011-12-07T06:35:42.113 に答える