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

问题描述 投票:0回答:3

如果我正确理解 Argparse,则位置参数是用户可以指定的必需参数。我需要使用 argparse 创建一个位置参数,其中用户可以指定在他/她调出 -h 选项时显示的某种类型的参数。我尝试过使用 add_argument_group 但当您调出 -h 选项时,它仅显示带有其他参数描述的标题。

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 函数?

python file argparse
3个回答
2
投票

使用

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()

0
投票

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

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() 返回的对象访问用户输入的值。


0
投票

使用选项分组功能使用

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()
© www.soinside.com 2019 - 2024. All rights reserved.