则会出现错误消息

则会出现错误消息

本文介绍了文件作为argparse的命令行参数-如果参数无效,则会出现错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在像这样使用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=opentype=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的命令行参数-如果参数无效,则会出现错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:40