未提供位置参数时打印帮助

时间:2017-01-16 07:49:19

标签: python argparse

我正在尝试执行我的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

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

1 个答案:

答案 0 :(得分: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)

`