python - argparse 多个可选参数
问题描述
我正在编写一个在一个或多个输入文件中搜索正则表达式的脚本。如果没有提供输入文件(或者有一个"-"
代替文件),它应该在stdin
.
例子:myscript.py [-h] [-u | -c | -m] [infile [infile ...]] regex
我不明白的是 - 它如何区分文件名和正则表达式?假设我输入myscript.py file1 file2 regex
. 它怎么知道这regex
是一个正则表达式而不是另一个文件?
我的代码如下:
def init_parser():
parser = argparse.ArgumentParser(
description="The script searches one or more named input files for lines\
containing a match to a regular expression pattern."
)
parser.add_argument(
'-f','--infile', nargs='*', type=argparse.FileType('r'), default='-',
help='the name of the file(s) to search.'
)
parser.add_argument('regex', help='the regular expression.')
group = parser.add_mutually_exclusive_group()
group.add_argument(
'-u', '--underscore', action='store_true',
help='prints "^" under the matching text.'
)
group.add_argument(
'-c', '--color', action='store_true',
help='highlights matching text.'
)
group.add_argument(
'-m', '--machine', action='store_true',
help='generates machine readable output.'
)
return parser
由于没有指定正则表达式的标志,脚本无法区分文件和正则表达式。如果我没有指定文件(因为我希望它从中读取stdin
)它认为我的正则表达式是一个文件并且它失败了。
解决方案
假设您将始终在命令行上有一个正则表达式,如果您首先放置正则表达式参数,然后是 infile,这将采用您指定的其他位置参数:
parser.add_argument('regex', help='the regular expression.')
parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), help='the name of the file(s) to search.')
推荐阅读
- php - Mariadb 错误:此 MariaDB 不允许使用的命令
- javascript - 如何通过道具 [REACT.JS] 将图像 url 从父组件传递到子组件
- shopify - Shopify 自定义结帐流程
- spring-boot - 为什么 jasypt PBE 不能在服务器上运行但在本地运行?
- angular - 初始化输入时缺少 asyncValidator (Angular 7.0.1)
- python - 使用命令行将 matplotlib 图保存到文件中,而不使用 plt.save()
- android - 将 sharedIntent 显示为列表,而不是网格
- vb.net - 如何在VB的剪贴板中添加图像、文档?
- jenkins - 为 Jenkins 自由式项目归档工件时出错?
- r - 读取 SAS 数据集 R sas7bdat 包