1

私のアプリケーションでは、次のようなパーサーがあります。

description = ("Cluster a matrix using bootstrap resampling or "
               "Bayesian hierarchical clustering.")
sub_description = ("Use these commands to cluster data depending on "
                   "the algorithm.")

parser = argparse.ArgumentParser(description=description, add_help=False)
subparsers = parser.add_subparsers(title="Sub-commands",
                                   description=sub_description)
parser.add_argument("--no-logfile", action="store_true", default=False,
                    help="Don't log to file, use stdout")
parser.add_argument("source", metavar="FILE",
                    help="Source data to cluster")
parser.add_argument("destination", metavar="FILE",
                     help="File name for clustering results")

次に、次のような一連のサブパーサーを追加します(関数が長いため、関数を使用します)。

setup_pvclust_parser(subparsers, parser)
setup_native_parser(subparsers, parser)

これらの呼び出し(1つの例):

def setup_pvclust_parser(subparser, parent=None):

    pvclust_description = ("Perform multiscale bootstrap resampling "
                           "(Shimodaira et al., 2002)")
    pvclust_commands = subparser.add_parser("bootstrap",
        description=pvclust_description, parents=[parent])
     pvclust_commands.add_argument("-b", "--boot", type=int,
                                   metavar="BOOT",
                                   help="Number of permutations",
                                   default=100)

    # Other long list of options...

    pvclust_commands.set_defaults(func=cluster_pvclust) # The function doing the processing

問題は、どういうわけかコマンドラインの解析が失敗することです。それはどこかで私のせいだと確信しています。実行時の例:

  my_program.py bootstrap --boot 10 --no-logfile test.txt test.pdf

  my_program.py bootstrap: error: too few arguments

構文解析がどういうわけか間違っているかのように。サブパーサー呼び出しでparents=[]を削除すると、この動作はなくなりますが、大量の重複が発生するため、この動作は避けたいと思います。

編集:呼び出しのsubparsers後にadd_argument呼び出しを移動すると、問題の一部が修正されます。ただし、パーサーはサブコマンドを適切に解析できなくなりました。

my_program.py bootstrap --boot 100 --no-logfile test.txt test.pdf

my_program.py: error: invalid choice: 'test.txt' (choose from 'bootstrap', 'native')
4

1 に答える 1