Python Argparse получить полную информацию об использовании, когда не приведены аргументы - PullRequest
2 голосов
/ 02 апреля 2019

Работа над сценарием, чтобы сделать запуск контейнеров 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 Ответ

4 голосов
/ 02 апреля 2019

Вы можете переопределить метод ArgumentParser.print_usage с помощью метода ArgumentParser.print_help:

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