I want to:
- pass one or more ()*
namedarguments to a python script, - pass an optional
filterargument also to the script, - match all other
argumentsagainst thefilter(if supplied), - add all
arguments(matching thefilterargument if supplied) to anarray[], - quit with an
error message and syntax helpif noargumentsare given or if only afilterargument is given (thefilteris dependent upon - requires - otherarguments).
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:
- there MUST be at least one
argument, - there MUST be at most one
filterargument,
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}')
Forget the mutually exclusive group.
To get
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
argsnamespace likeUse
to test if filter was provided or not
to test is that was provided or not.
Iterate on
args.argto apply thefilterand build a new list. A for loop or list comprehension should work.The
argargument could also be anargs='+'instead ofaction='append'.If both
argsattributes are empty, you could callparse.print_usage()and exit.