Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding default argparse -h behaviour

Tags:

I have a certain config file which calls upon its plugins. It's possible to pass arguments to those plugins. This config file also lets me call arbitary commands at runtime.

The plugins use many arguments: one of them is -h and it does not stand for --help. Now, my issue is that I want to call my own Python script as well as pass it some arguments. I'm using argparse and wanting to be consistent with the rest of the config, I created a -h flag. To my surprise, argparse just gives me argparse.ArgumentError: argument -h/--help: conflicting option string(s): -h instead of minding its own business.

Is there a way to stop this from happening?

I am well aware that most people expect -h to give help but it's my own script and I think I know better what I want to use a flag for than the argparse devs.

like image 493
Mateusz Kowalczyk Avatar asked Feb 19 '13 06:02

Mateusz Kowalczyk


2 Answers

Look in the argparse documentation for the ArgumentParser arguments. There's one called add_help, which defaults to True.

parser = argparse.ArgumentParser('Cool', add_help=False) parser.add_argument('-h', '--hi', action='store_true', dest='hi') 

This works as expected.

like image 60
deadfoxygrandpa Avatar answered Sep 21 '22 22:09

deadfoxygrandpa


If you give the ArgumentParser a conflict_handler="resolve" argument, adding your own -h will override the existing one, while keeping --help functional.

#!/usr/bin/env python3 import argparse parse = argparse.ArgumentParser(conflict_handler="resolve") parse.add_argument("-h", "--hello") print(parse.parse_args()) 
like image 31
Alcaro Avatar answered Sep 20 '22 22:09

Alcaro