如果未提供任何参数,则python argparse将获得完整的使用情况信息

时间:2019-04-01 21:15:57

标签: python python-3.x argparse

使用脚本使启动lxc容器更加灵活;根据测试用户需要更好的帮助:)

#!/usr/bin/env python3
import argparse
import sys

def parse_args():
    parser = argparse.ArgumentParser(description="stand up an lxc container")
    if len(sys.argv) == 1:
        parser.format_help()
    parser.add_argument("-4i", "--fouri", type=str, help="IPv4 address, if containername NOT in DNS (yet)")
    parser.add_argument("-6i", "--sixi", nargs='?', const=1, default="::2", type=str, help="IPv6 address, if containername NOT in DNS (yet)")
    parser.add_argument("-4m", "--fourm", nargs='?', const=1, default="24", type=str, help="IPv4 netmask, if unset '24'")
    parser.add_argument("-6m", "--sixm", nargs='?', const=1, default="64", type=str, help="IPv6 netmask, if unset '64'")
    parser.add_argument("-4g", "--fourg", type=str, help="IPv4 gateway")
    parser.add_argument("-6g", "--sixg", nargs='?', const=1, default="::1", type=str, help="IPv6 gateway")
    parser.add_argument("-i", type=str, required=True, help="name of the image to launch from")
    parser.add_argument("-c", type=str, required=True, help="hostname of the container to be launched")
    return parser.parse_known_args()


def main():
    args, unknown = parse_args()

if __name__ == "__main__":
    main()

如果不带任何参数调用脚本,这就是我得到的:

./test.py
usage: test.py [-h] [-4i FOURI] [-6i [SIXI]] [-4m [FOURM]] [-6m [SIXM]]
               [-4g FOURG] [-6g [SIXG]] -i I -c C
test.py: error: the following arguments are required: -i, -c

我想获得与用--help / -h调用时得到的输出相同的输出:

./test.py -h
usage: test.py [-h] [-4i FOURI] [-6i [SIXI]] [-4m [FOURM]] [-6m [SIXM]]
               [-4g FOURG] [-6g [SIXG]] -i I -c C

stand up an lxc container

optional arguments:
  -h, --help            show this help message and exit
  -4i FOURI, --fouri FOURI
                        IPv4 address, if containername NOT in DNS (yet)
  -6i [SIXI], --sixi [SIXI]
                        IPv6 address, if containername NOT in DNS (yet)
  -4m [FOURM], --fourm [FOURM]
                        IPv4 netmask, if unset '24'
  -6m [SIXM], --sixm [SIXM]
                        IPv6 netmask, if unset '64'
  -4g FOURG, --fourg FOURG
                        IPv4 gateway
  -6g [SIXG], --sixg [SIXG]
                        IPv6 gateway
  -i I                  name of the image to launch from
  -c C                  hostname of the container to be launched

1 个答案:

答案 0 :(得分:4)

您可以使用ArgumentParser.print_usage方法覆盖ArgumentParser.print_help方法:

def parse_args():
    parser = argparse.ArgumentParser(description="stand up an lxc container")
    parser.print_usage = parser.print_help
    ...