python argparse在没有给出参数时获取完整的使用信息

tin*_*ink 3 python argparse python-3.x

编写脚本使启动 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()
Run Code Online (Sandbox Code Playgroud)

如果我调用没有任何参数的脚本,我会得到以下结果:

./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
Run Code Online (Sandbox Code Playgroud)

如果我使用以下命令调用它,我想获得相同的输出--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
Run Code Online (Sandbox Code Playgroud)

blh*_*ing 5

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

def parse_args():
    parser = argparse.ArgumentParser(description="stand up an lxc container")
    parser.print_usage = parser.print_help
    ...
Run Code Online (Sandbox Code Playgroud)