python 带有强制输入文件参数的 argparse

python argparse with mandatory input file argument

如何使用前缀 -i 或 --input 向解析器添加强制选项以指定脚本的输入文件?

提供的值应放入 infile 变量

从文档中提炼出来,一个简约的答案是

import argparse

#Create the parser
parser = argparse.ArgumentParser(description='Does some stuff with an input file.')

#add the argument
parser.add_argument('-i', '--input', dest='infile',  type=file, required=True,
                metavar='INPUT_FILE', help='The input file to the script.')

#parse and assign to the variable
args = parser.parse_args()
infile=args.infile

请注意,如果指定的文件不存在,解析器将抛出 IOError。删除 type=file 参数将默认读取一个字符串,并让您稍后处理参数上的文件操作。