I want to:

  1. pass one or more ()* named arguments to a python script,
  2. pass an optional filter argument also to the script,
  3. match all other arguments against the filter (if supplied),
  4. add all arguments (matching the filter argument if supplied) to an array[],
  5. quit with an error message and syntax help if no arguments are given or if only a filter argument is given (the filter is dependent upon - requires - other arguments).

For example:

python script.py

should generate the usage help message then quit.

python script.py --arg string

should add the arg string to the array[].

python script.py --arg string1 --arg string2 --arg string3

should add all arguments to the array[].

python script.py --arg string1 --arg string2 --arg string3 --filter '*2*'

should add only those arguments that match the filter to the array[], so in this case it would only add string2 to the array[] and ignore the rest.

So:

  1. there MUST be at least one argument,
  2. there MUST be at most one filter argument,

Here is an example, but it does not work as expected because I don't think group = parser.add_mutually_exclusive_group(required=True) operates in the way I have explained above - it just requires either argument but does not specify which one is required:

import argparse

# Create an ArgumentParser object
parser = argparse.ArgumentParser(description='Dependent argument testing')

# Create a mutually exclusive group for the --arg and --filter options
group = parser.add_mutually_exclusive_group(required=True)

# Define the --arg argument (required)
group.add_argument('--arg', type=str, help='Specify the argument')

# Define the --filter argument (optional)
group.add_argument('--filter', type=str, help='Specify the filter (optional)')

# Parse the command-line arguments
args = parser.parse_args()

# Access the values of the arguments
if args.arg:
    print(f'Argument: {args.arg}')
if args.filter:
    print(f'Filter: {args.filter}')
1

There are 1 best solutions below

0
hpaulj On

Forget the mutually exclusive group.

To get

script.py --arg string1 --arg string2 --arg string3 --filter '*2*'

Use '-h/--help' to get automatic usage and help. Trying to get usage when not given any arguments is possible, but I don't think it's worth the extra effort.

Define '--arg' as an 'append', and you can string as many as you want.

'--filter' can be a default 'store'.

Include a print(args) to test.

The rest is post parsing logic and code.

edit

I'd expect a args namespace like

Namespace('arg'=['arg1','arg2','arg3'], 'filter'='*2*')

Use

if args.filter is None:
    ...

to test if filter was provided or not

if args.arg is empty:
     .....

to test is that was provided or not.

Iterate on args.arg to apply the filter and build a new list. A for loop or list comprehension should work.

The arg argument could also be a nargs='+' instead of action='append'.

If both args attributes are empty, you could call parse.print_usage() and exit.