简体   繁体   English

接受可选多个输入的Python脚本

[英]Python script accepting optional multiple inputs

Say I have something like this: 说我有这样的事情:

python example.py -i input.txt

where the script is required to have at least one input, and I want it to have the option of accepting multiple inputs such as: 要求脚本至少具有一个输入的位置,而我希望它可以选择接受多个输入,例如:

python example.py -i input1.txt -i input2.txt -i input3.txt

I've looked into Python's argparse module so I have something like: 我已经研究了Python的argparse模块,所以我有类似以下内容:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-i", help="takes in an input file", action="store_true")

But I'm not exactly sure how to make it so it can have multiple inputs and be able to retrieve them. 但是我不确定如何使它具有多个输入并能够检索它们。

You can allow an option to receive any number of arguments using the nargs parameter : 您可以使用nargs参数允许一个选项接收任意数量的参数

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-i', nargs='+')
>>> parser.parse_args('-i input1.txt input2.txt input3.txt'.split())
Namespace(i=['input1.txt', 'input2.txt', 'input3.txt'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM