文件作为 argparse 的命令行参数 - 如果参数无效,则会出现错误消息 [英] File as command line argument for argparse - error message if argument is not valid
问题描述
我目前正在使用这样的 argparse:
I am currently using argparse like this:
import argparse
from argparse import ArgumentParser
parser = ArgumentParser(description="ikjMatrix multiplication")
parser.add_argument("-i", dest="filename", required=True,
help="input file with two matrices", metavar="FILE")
args = parser.parse_args()
A, B = read(args.filename)
C = ikjMatrixProduct(A, B)
printMatrix(C)
现在我要注意的是,-i
的参数应该是一个可读文件.我该怎么做?
Now I would like to note, that the argument of -i
should be a readable file. How can I do that?
我已经尝试添加 type=open
, type=argparse.FileType('r')
并且它们起作用了,但是如果文件无效,我会喜欢收到错误信息.我该怎么做?
I've tried adding type=open
, type=argparse.FileType('r')
and they worked, but if the file is not valid, I would like to get an error message. How can I do that?
推荐答案
其实很简单.您只需要编写一个函数来检查文件是否有效,否则写入错误.将该函数与 type
选项一起使用.请注意,您可以通过子类化 argparse.Action
来获得更多幻想并创建自定义操作,但我认为这里没有必要.在我的示例中,我返回一个打开的文件句柄(见下文):
It's pretty easy actually. You just need to write a function which checks if the file is valid and writes an error otherwise. Use that function with the type
option. Note that you could get more fancy and create a custom action by subclassing argparse.Action
, but I don't think that is necessary here. In my example, I return an open file handle (see below):
#!/usr/bin/env python
from argparse import ArgumentParser
import os.path
def is_valid_file(parser, arg):
if not os.path.exists(arg):
parser.error("The file %s does not exist!" % arg)
else:
return open(arg, 'r') # return an open file handle
parser = ArgumentParser(description="ikjMatrix multiplication")
parser.add_argument("-i", dest="filename", required=True,
help="input file with two matrices", metavar="FILE",
type=lambda x: is_valid_file(parser, x))
args = parser.parse_args()
A, B = read(args.filename)
C = ikjMatrixProduct(A, B)
printMatrix(C)
这篇关于文件作为 argparse 的命令行参数 - 如果参数无效,则会出现错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!