【问题标题】:python argparse how to continue the program after the [-h] command?python argparse如何在[-h]命令后继续程序?
【发布时间】:2018-04-13 16:12:36
【问题描述】:

我正在使用 argparse 来编写解释器。并面临一个问题。

while True:
    cmd = input('>>>')
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', help='foo')
    parser.parse_args(cmd.split())

当我输入 [-h] 命令时,它会退出程序。

>>>-h
usage: test.py [-h] [-f F]

optional arguments:
-h, --help  show this help message and exit
-f F        foo

现在,我只想要“显示此帮助消息”而不是“退出”。那请问我该怎么办?

【问题讨论】:

  • 好吧 -h 用于帮助命令,它为您提供帮助摘要,它应该像这样工作
  • 也许你应该试试cmd 模块。使用argparse 进行命令行解析听起来并不理想。

标签: python argparse


【解决方案1】:

这可以通过删除预定义的帮助命令并添加自己的来完成:

import argparse

while True:
    cmd = input('>>>')
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('-h', '--help', action='store_true',
            help = 'show this help message')
    parser.add_argument('-f', help='foo')
    args = parser.parse_args(cmd.split())
    if args.help:
        parser.print_help()

【讨论】:

  • 是的,一些著名的工具能够同时打印帮助。很好的答案。
猜你喜欢
  • 2011-02-09
  • 1970-01-01
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
相关资源
最近更新 更多