gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:11:45 27 4
gpt4 key购买 nike

正在编写脚本,使 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

最佳答案

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

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

关于python argparse 在没有给出参数时获取完整的使用信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55463677/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com