【问题标题】:Print help when positional arguments not provided未提供位置参数时打印帮助
【发布时间】:2017-05-31 00:17:54
【问题描述】:

我正在尝试执行我的 Python 程序。它使用一个位置参数。当没有提供位置参数时,我想打印帮助。但我得到的只是

error : too few arguments

这是 Python 代码:

parser = argparse.ArgumentParser(
        description = '''My Script ''')
parser.add_argument('I', type=str, help='Provide the release log file')
args = parser.parse_args()

当没有指定位置参数时,我期待以下输出:

usage: script.py [-h] I

My Script

positional arguments:
  I           Provide the release log file

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

任何想法如何实现这一点将不胜感激。

【问题讨论】:

    标签: python argparse


    【解决方案1】:

    argparse 不能这样工作。您需要使用 -h 参数寻求帮助。否则它只会给出usage 以及错误消息。

    0015:~/mypy$ python3 stack41671660.py 
    usage: stack41671660.py [-h] I
    stack41671660.py: error: the following arguments are required: I
    0015:~/mypy$ python stack41671660.py 
    usage: stack41671660.py [-h] I
    stack41671660.py: error: too few arguments
    0015:~/mypy$ python stack41671660.py -h
    usage: stack41671660.py [-h] I
    
    My Script
    
    positional arguments:
      I           Provide the release log file
    
    optional arguments:
      -h, --help  show this help message and exit
    

    您可以使用nargs='?' 将位置参数设置为“可选”,并为默认值添加测试:

    print(args)
    if args.I is None:
        parser.print_help()
    

    样本运行:

    0016:~/mypy$ python stack41671660.py 
    Namespace(I=None)
    usage: stack41671660.py [-h] [I]
    
    My Script
    
    positional arguments:
      I           Provide the release log file
    
    optional arguments:
      -h, --help  show this help message and exit
    0019:~/mypy$ python stack41671660.py 2323
    Namespace(I='2323')
    

    另一种选择是自定义parser.error 方法,使其执行print_help 而不是print_usage。这将影响所有解析错误,而不仅仅是这个丢失的位置。

    def error(self, message):
        """error(message: string)
    
        Prints a usage message incorporating the message to stderr and
        exits.
    
        If you override this in a subclass, it should not return -- it
        should either exit or raise an exception.
        """
        # self.print_usage(_sys.stderr)
        self.print_help(_sys.stderr)
        args = {'prog': self.prog, 'message': message}
        self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
    

    `

    【讨论】:

      猜你喜欢
      • 2012-12-17
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 2012-04-05
      相关资源
      最近更新 更多