Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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. </p> <p>You can use a custom action:</p> <pre><code>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) </code></pre> <p>And this is what you get:</p> <pre><code>&gt;&gt;&gt; parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree']) Namespace(a=True, b=True, input=['fileone', 'filetwo', 'filethree']) </code></pre> <p>Or you can modify the resulted namespace like this:</p> <pre><code>&gt;&gt;&gt; import argparse &gt;&gt;&gt; parser = argparse.ArgumentParser() &gt;&gt;&gt; parser.add_argument('-a', nargs='+') &gt;&gt;&gt; parser.add_argument('-b', nargs='+') &gt;&gt;&gt; parser.add_argument('input', nargs='+') &gt;&gt;&gt; result = parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree']) &gt;&gt;&gt; inputs = [] &gt;&gt;&gt; inputs.extend(result.a) &gt;&gt;&gt; inputs.extend(result.b) &gt;&gt;&gt; inputs.extend(result.input) &gt;&gt;&gt; modified = argparse.Namespace( a = result.a != [], b = result.b != [], input = inputs) </code></pre> <p>And this is what you get:</p> <pre><code>&gt;&gt;&gt; modified Namespace(a=True, b=True, input=['filetwo', 'filethree', 'fileone']) </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload