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

发布于 2024-10-01 11:21:30 字数 962 浏览 3 评论 0原文

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

# 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)

是否有更好的方法来执行此操作,最好全部在解析器内?最后一个错误看起来有点不合适,如果我能让地址的 nargs 取决于 --odam 或 ---odas 是否通过,那就太好了。我可以创建一个子解析器,但这会使帮助看起来有点奇怪,因为它会省略命令的地址部分。

I'm writing a server querying tool, and I have a little bit of code to parse arguments at the very top:

# 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)

Is there a nicer way to do this, preferably all within the parser? That last error looks a little out of place, and it would be nice if I could make nargs for address depend on if --odam or ---odas is passed. I could create a subparser, but that would make help look a little odd since it would leave off the addresses part of the command.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

属性 2024-10-08 11:21:31

您可以使用自定义 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')

You can do this with an custom 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()

yields

% 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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文