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

2024-04-25 20:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我正确理解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作为参数,则脚本应该运行。但是,如果I没有从列出的3个选项中指定文件类型,则脚本将无法运行。在

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


Tags: csvthetxt脚本addparserinput参数
3条回答

使用选项分组功能使用^{}而不是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()

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

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

使用^{}参数强制用户从一组受限制的值中进行选择。在

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

相关问题 更多 >