即使在 argparse 中的 --help 参数上也允许 Python 脚本到 运行

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

我在 python 中使用 Argparse 模块来开发命令行工具。 这是解析器代码:

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 

然而,当我 运行 代码 python foo.py --help 时,它从不 运行 脚本 post 解析参数。我能做些什么来阻止这种行为。我想分析解析器结果,即使只是要求 --help 开关。

想知道即使在 --help 已被使用后我能做些什么来继续脚本

add_help parameter for argparse.ArgumentParser 设置为 False 以禁用 -h--help:

parser=argparse.ArgumentParser(add_help=False)

然后,添加--help:

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

正如用户 Thierry Lathuille 在评论中所说,--help 用于打印帮助和 exit

如果出于某种原因你想打印帮助和运行脚本,你可以添加自己的参数像这样:

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!')

如果脚本的名字是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!

编辑: 如果您坚持使用 --help 而不是自定义参数:

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!')

如果脚本的名字是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!

注意:你不应该这样做,因为它不尊重既定的用法并且可能会打扰用户。对于剩下的答案,我将假设您已经知道它并且有充分的理由不遵守常见用法。

我可以成像的唯一方法是删除标准 -h|--help 处理并安装你自己的:

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

然后在选项处理中,你只需添加:

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