允许Python脚本甚至在argparse中的--help参数上运行



我使用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时,它从不在解析参数后运行脚本。我能做些什么来制止这种行为吗。我想分析解析器的结果,即使只是要求它切换--help

我想知道在使用了--help之后,我能做些什么来继续脚本

备注:您不应该这样做,因为它不尊重既定用法,可能会干扰用户。对于剩下的答案,我认为你已经意识到了这一点,并且有严重的理由不尊重常见用法。

我可以成像的唯一方法是删除标准的-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()

正如用户Thierry Lathuille在评论中所说,--help旨在打印帮助并退出。

如果出于某种原因,您想打印帮助并运行脚本,您可以添加自己的参数,如下所示:

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!

argparse.ArgumentParseradd_help参数设置为False以禁用-h--help:

parser=argparse.ArgumentParser(add_help=False)

然后,添加--help:

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

最新更新