12

私は、相互に排他的な2つの引数と、それらの引数の1つでのみ意味をなすオプションを持つスクリプトを作成しています。意味のない引数で呼び出すと失敗するようにargparseを設定しようとしています。

明確にするために:

-m -f理にかなっている

-s理にかなっている

-s -fエラーをスローする必要があります

引数は問題ありません。

私が持っているコードは次のとおりです。

parser = argparse.ArgumentParser(description='Lookup servers by ip address from host file')
parser.add_argument('host', nargs=1,
            help="ip address to lookup")
main_group = parser.add_mutually_exclusive_group()
mysql_group = main_group.add_argument_group()
main_group.add_argument("-s", "--ssh", dest='ssh', action='store_true',
            default=False,
            help='Connect to this machine via ssh, instead of printing hostname')
mysql_group.add_argument("-m", "--mysql", dest='mysql', action='store_true',
            default=False,
            help='Start a mysql tunnel to the host, instead of printing hostname')
mysql_group.add_argument("-f", "--firefox", dest='firefox', action='store_true',
            default=False,
            help='Start a firefox session to the remotemyadmin instance')

それが吐き出すので、それはうまくいきません

 usage: whichboom [-h] [-s] [-m] [-f] host

私が期待するものではなく:

 usage: whichboom [-h] [-s | [-h] [-s]] host

またはそのような。

 whichboom -s -f -m 116

また、エラーはスローされません。

4

2 に答える 2

8

引数グループが混同されているだけです。コードでは、相互に排他的なグループに1つのオプションのみを割り当てます。私はあなたが欲しいものは次のとおりだと思います:

parser = argparse.ArgumentParser(description='Lookup servers by ip address from host file')
parser.add_argument('host', nargs=1,
            help="ip address to lookup")
main_group = parser.add_mutually_exclusive_group()
mysql_group = main_group.add_argument_group()
main_group.add_argument("-s", "--ssh", dest='ssh', action='store_true',
            default=False,
            help='Connect to this machine via ssh, instead of printing hostname')
mysql_group.add_argument("-m", "--mysql", dest='mysql', action='store_true',
            default=False,
            help='Start a mysql tunnel to the host, instead of printing hostname')
main_group.add_argument("-f", "--firefox", dest='firefox', action='store_true',
            default=False,
            help='Start a firefox session to the remotemyadmin instance')

相互に排他的なグループ全体をスキップして、次のようなものを追加することができます。

usage = 'whichboom [-h] [-s | [-h] [-s]] host'
parser = argparse.ArgumentParser(description, usage)
options, args = parser.parse_args()
if options.ssh and options.firefox:
    parser.print_help()
    sys.exit()
于 2010-12-16T23:09:21.657 に答える
2

usageパーサーを作成するときに引数を追加します。

usage = "usage: whichboom [-h] [-s | [-h] [-s]] host"
description = "Lookup servers by ip address from host file"
parser = argparse.ArgumentParser(description=description, usage=usage)

ソース:http ://docs.python.org/dev/library/argparse.html#usage

于 2010-12-16T23:04:30.367 に答える