使用Python和argparse的多个位置参数 [英] Multiple positional arguments with Python and argparse

查看:75
本文介绍了使用Python和argparse的多个位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用argparse来解析我正在处理的程序的命令行参数.本质上,我需要支持在可选参数中散布的多个位置参数,但是无法使argparse在这种情况下起作用.在实际程序中,我使用的是自定义操作(每次找到位置参数时,我都需要存储名称空间的快照),但是可以通过append操作来复制我遇到的问题:

I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot of the namespace each time a positional argument is found), but the problem I'm having can be replicated with the append action:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-a', action='store_true')
>>> parser.add_argument('-b', action='store_true')
>>> parser.add_argument('input', action='append')
>>> parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])
usage: ipython [-h] [-a] [-b] input
ipython: error: unrecognized arguments: filetwo filethree

我希望这产生命名空间(a=True, b=True, input=['fileone', 'filetwo', 'filethree']),但无法看到如何执行此操作-如果确实可以的话.我看不到文档或Google中的任何一种说法,说这是可能的,尽管这是完全可能的(可能吗?),但我已经忽略了一些东西.有人有什么建议吗?

I'd like this to result in the namespace (a=True, b=True, input=['fileone', 'filetwo', 'filethree']), but cannot see how to do this - if indeed it can. I can't see anything in the docs or Google which says one way or the other if this is possible, although its quite possible (likely?) I've overlooked something. Does anyone have any suggestions?

推荐答案

srgerg关于位置参数的定义是正确的.为了获得所需的结果,您必须接受它们作为可选参数,并根据需要修改结果命名空间.

srgerg was right about the definition of positional arguments. In order to get the result you want, You have to accept them as optional arguments, and modify the resulted namespace according to your need.

您可以使用自定义操作:

You can use a custom action:

class MyAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):

        # Set optional arguments to True or False
        if option_string:
            attr = True if values else False
            setattr(namespace, self.dest, attr)

        # Modify value of "input" in the namespace
        if hasattr(namespace, 'input'):
            current_values = getattr(namespace, 'input')
            try:
                current_values.extend(values)
            except AttributeError:
                current_values = values
            finally:
                setattr(namespace, 'input', current_values)
        else:
            setattr(namespace, 'input', values)

parser = argparse.ArgumentParser()
parser.add_argument('-a', nargs='+', action=MyAction)
parser.add_argument('-b', nargs='+', action=MyAction)
parser.add_argument('input', nargs='+', action=MyAction)

这就是你得到的:

>>> parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])
Namespace(a=True, b=True, input=['fileone', 'filetwo', 'filethree'])

或者您可以像这样修改结果名称空间:

Or you can modify the resulted namespace like this:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-a', nargs='+')
>>> parser.add_argument('-b', nargs='+')
>>> parser.add_argument('input', nargs='+')
>>> result = parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])

>>> inputs = []
>>> inputs.extend(result.a)
>>> inputs.extend(result.b)
>>> inputs.extend(result.input)

>>> modified = argparse.Namespace(
        a = result.a != [],
        b = result.b != [],
        input = inputs)

这就是你得到的:

>>> modified
Namespace(a=True, b=True, input=['filetwo', 'filethree', 'fileone'])

但是,这两种方法都导致可读性和可维护性降低.也许最好更改程序逻辑并以其他方式执行.

However, both method result in less readable and less maintainable code. Maybe it's better to change the program logic and do it in a different way.

这篇关于使用Python和argparse的多个位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆