Python argparse:nargs +或*取决于先前的参数

时间:2010-11-06 20:24:37

标签: python argparse

我正在编写一个服务器查询工具,我有一些代码可以解析最顶层的参数:

# Parse arguments
p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument('--odam', dest='query_type', action='store_const',
        const='odam', help="Odamex Master query.")
g.add_argument('--odas', dest='query_type', action='store_const',
        const='odas', help="Odamex Server query.")
p.add_argument('address', nargs='*')
args = p.parse_args()

# Default master server arguments.
if args.query_type == 'odam' and not args.address:
    args.address = [
            'master1.odamex.net:15000',
            'master2.odamex.net:15000',
            ]

# If we don't have any addresses by now, we can't go on.
if not args.address:
    print "If you are making a server query, you must pass an address."
    sys.exit(1)

有没有更好的方法来做到这一点,最好是在解析器中?最后一个错误看起来有点不合适,如果我可以根据--odam或--- odas传递地址取决于地址,那将会很好。我可以创建一个subparser,但这会使得帮助看起来有点奇怪,因为它会留下命令的地址部分。

1 个答案:

答案 0 :(得分:12)

您可以使用自定义argparse.Action

执行此操作
import argparse
import sys

class AddressAction(argparse.Action):
    def __call__(self, parser, args, values, option = None):
        args.address=values
        if args.query_type=='odam' and not args.address:
            args.address=[
                'master1.odamex.net:15000',
                'master2.odamex.net:15000',
                ]        
        if not args.address:
            parser.error("If you are making a server query, you must pass an address.")

p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument('--odam', dest='query_type', action='store_const',
        const='odam', help="Odamex Master query.")
g.add_argument('--odas', dest='query_type', action='store_const',
        const='odas', help="Odamex Server query.")
p.add_argument('address', nargs='*', action=AddressAction)
args = p.parse_args()

产量

% test.py --odas
If you are making a server query, you must pass an address.
% test.py --odam
Namespace(address=['master1.odamex.net:15000', 'master2.odamex.net:15000'], query_type='odam')
% test.py --odam 1 2 3
Namespace(address=['1', '2', '3'], query_type='odam')