使用 Argparse 创建具有多个选项的必需参数?

Using Argparse to create required argument with multiple options?

如果我对 Argparse 的理解正确,位置参数是用户可以指定的必需参数。我需要使用 argparse 创建一个位置参数,用户可以在其中指定在 he/she 显示 -h 选项时显示的特定类型的参数。我试过使用 add_argument_group,但当您调出 -h 选项时,它只会显示 header 以及其他参数的描述。

def Main():
    parser = argparse.ArgumentParser(description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter)
    parser.add_argument("input_directory",help = "The input directory where all of the files reside in")

    sub_parser = parser.add_argument_group('File Type')

    sub_parser.add_argument(".txt",help = "The input file is a .txt file")
    sub_parser.add_argument(".n12",help = "The input file is a .n12 file")
    sub_parser.add_argument(".csv",help = "The input file is a .csv file")

    parser.parse_args()

if __name__ == "__main__":
    Main()

所以当我运行脚本时,我应该指定为了运行脚本。如果我选择 .txt、.n12 或 .csv 作为我的参数,那么脚本应该 运行。但是,如果我没有从列出的这 3 个选项中指定文件类型,那么脚本将不会 运行。

是否有我缺少的 argparse 函数可以为位置参数指定多个选项?

我认为你把这件事想得太复杂了。如果我正确理解你的问题,你希望用户输入两个参数:一个目录名和一个文件类型。您的应用程序将只接受三个文件类型值。简单地这样做怎么样:

import argparse

def Main():
    parser = argparse.ArgumentParser(description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter)
    parser.add_argument("input_directory", help = "The input directory where all of the files reside in")
    parser.add_argument("file_type", help="One of: .txt, .n12, .csv")
    args = parser.parse_args()
    print(args)

if __name__ == "__main__":
    Main()

... 并添加应用程序逻辑以拒绝文件类型的无效值。

您通过 parse_args() 返回的对象访问用户输入的值。

使用 choices= 参数强制用户从一组受限制的值中进行选择。

import argparse

def Main():
    parser = argparse.ArgumentParser()
    parser.add_argument("input_directory",help = "The input directory where all of the files reside in")
    parser.add_argument("file_type", help = "File Type", choices=['.txt', '.n12', '.csv'])

    ns = parser.parse_args()
    print(ns)


if __name__ == "__main__":
    Main()

使用选项分组功能使用 add_mutually_exclusive_group() 而不是 add_argument_group()

import argparse


def Main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("input_directory", help="The input directory where all of the files reside in")

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("-txt", action='store_true', help="The input file is a .txt file")
    group.add_argument("-n12", action='store_true', help="The input file is a .n12 file")
    group.add_argument("-csv", action='store_true', help="The input file is a .csv file")

    print parser.parse_args()

if __name__ == "__main__":
    Main()