I’m developing a Python command-line tool using argparse with multiple modules, each having its own set of arguments. I’m using separate classes to define each module’s arguments and integrate them into a main script. However, I’m encountering an issue where the -h/--help
argument is conflicting when running the help command for a subcommand.
Here’s a simplified version of my setup:
fastp_arguments.py:
import argparse
class FastpArguments:
def __init__(self, args=None):
self.parser = argparse.ArgumentParser(description="fastp arguments.", add_help=False)
self.args = args if args is not None else []
self._initialize_parser()
def _initialize_parser(self):
fastp_args = self.parser.add_argument_group("Fastp Options")
fastp_args.add_argument("-i", "--in1", required=True, help="read1 input file name")
fastp_args.add_argument("-o", "--out1", required=True, help="read1 output file name")
fastp_args.add_argument("-I", "--in2", help="read2 input file name")
fastp_args.add_argument("-O", "--out2", help="read2 output file name")
def parse_arguments(self):
self.args = self.parser.parse_args(self.args)
return self.args
main.py:
import argparse
from fastp_arguments import FastpArguments
def main():
parser = argparse.ArgumentParser(description='My Tool', add_help=False)
parser.add_argument('-h', '--help', action='help', help='Show this help message and exit')
subparsers = parser.add_subparsers(dest='tool', help='Sub-command help')
fastp_args_class = FastpArguments()
fastp_parser = subparsers.add_parser('fastp', help='Fastp Help', parents=[fastp_args_class.parser], add_help=False)
fastp_parser.add_argument('-h', '--help', action='help', help='Show this help message and exit')
args = parser.parse_args()
if args.tool == 'fastp':
fastp_args_class.args = args
fastp_args_class.parse_arguments()
print("Fastp selected")
print(fastp_args_class.args)
else:
parser.print_help()
if __name__ == '__main__':
main()
Issue
When I run seqsightqc fastp -h, I get the following error:
argparse.ArgumentError: argument -h/--help: conflicting option strings: -h, --help
What I've Tried
Setting add_help=False for the parent parsers.
Manually adding the -h/--help argument to both the top-level parser and subparsers.
Desired Outcome
I want to be able to run seqsightqc fastp -h and see the help message for the fastp subcommand without any conflicts or errors.
Question
How can I resolve the argparse conflict with the -h/–help argument when using subcommands in this setup?
Specifically, I want the final out of -h
to print all the arguments of all the modules!