简体   繁体   中英

Allowing Python Script to run even on --help argument in argparse

I am using Argparse module in python for developing a Command Line Tool. Here's the parser code:

from argparse import ArgumentParser

def arguments():
    parser = ArgumentParser() 
    parser.add_argument('-c' , '--comms' , action = "store" , default = None , type = str , dest = "command",
                        help = 'Choosing a Command')
    parser.add_argument( '-s' , '--search' , action = 'store' , default = None , type = str , dest = 'search_path'  ,
                        help = 'Search for a command' )
    parser.add_argument(  '-f' , '--config' , action = 'store_true' ,
                        help = 'Show the present configuration')

    parser.add_argument('--flush_details' , action = "store_false" , 
                        help = "Flushes the current commands buffer") 
    
    return parser.parse_args() 

def main():
    
    parser_results = arguments() 

    #More code comes here to analyze the results 

However, when I run the code python foo.py --help , it never runs the script post parsing the arguments. Is there anything I can do to stop the behaviour. I want to analyse the parser results even if it is just asked for --help switch.

Would like to know what can I do to continue the script even after --help has been used

Remark: you should not do that, because it does not respect established usages and may disturb users. For the remaining of the answer I shall assume that you are aware of it and have serious reasons for not respecting common usages.

The only way I can imaging is to remove the standard -h|--help processing and install your own:

parser = ArgumentParser(add_help=False) 
parser.add_argument('-h' , '--help', help = 'show this help', action='store_true')
...

Then in option processing, you just add:

parser_results = parser.parse_args()
if parser_results.help:
    parser.print_help()

Set the add_help parameter for argparse.ArgumentParser to False to disable -h and --help :

parser=argparse.ArgumentParser(add_help=False)

Then, add --help :

parser.add_argument('--help',action='store_true')

As user Thierry Lathuille has said in the comments, --help is meant to print the help and exit .

If for some reason you want to print the help and run the script , you can add your own argument like so:

import argparse

parser = argparse.ArgumentParser(description="This script prints Hello World!")
parser.add_argument("-rh", "--runhelp", action="store_true", help="Print help and run function")

if __name__ == "__main__":
    args = parser.parse_args()
    if args.runhelp:
        parser.print_help()

    print('Hello World!')

If the name of the script is main.py :

>>> python main.py -rh
usage: main.py [-h] [-rh]

This script prints Hello World!

optional arguments:
  -h, --help      show this help message and exit
  -rh, --runhelp  Print help and run function
Hello World!

EDIT: If you insist on using --help instead of a custom argument:

import argparse

parser = argparse.ArgumentParser(description="This script prints Hello World!", add_help=False)
parser.add_argument("-h", "--help", action="store_true", help="Print help and run function")

if __name__ == "__main__":
    args = parser.parse_args()
    if args.help:
        parser.print_help()

    print('Hello World!')

If the name of the script is main.py :

>>> python main.py -h
usage: main.py [-h]

This script prints Hello World!

optional arguments:
  -h, --help  Print help and run function
Hello World!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM