首页 > 解决方案 > 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)它认为我的正则表达式是一个文件并且它失败了。

标签: python

解决方案


假设您将始终在命令行上有一个正则表达式,如果您首先放置正则表达式参数,然后是 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.')

推荐阅读