11

我正在编写一个服务器查询工具,并且我有一些代码来解析最顶部的参数:

# 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 是否通过而为地址设置 nargs 那就太好了。我可以创建一个子解析器,但这会使帮助看起来有点奇怪,因为它会省略命令的地址部分。

4

1 回答 1

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')
于 2010-11-06T21:49:45.503 回答