gpt4 book ai didi

python - 文件作为 argparse 的命令行参数 - 如果参数无效,则会出现错误消息

转载 作者:IT老高 更新时间:2023-10-28 20:31:21 26 4
gpt4 key购买 nike

我目前正在像这样使用 argparse:

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 的参数应该是一个可读文件。我该怎么做?

我尝试添加 type=opentype=argparse.FileType('r') 并且它们有效,但如果文件无效,我会喜欢收到错误消息。我该怎么做?

最佳答案

其实很简单。您只需要编写一个函数来检查文件是否有效,否则会写入错误。将该函数与 type 选项一起使用。请注意,您可以通过子类化 argparse.Action 来获得更多花哨并创建自定义操作,但我认为这里没有必要。在我的示例中,我返回一个打开的文件句柄(见下文):

#!/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)

关于python - 文件作为 argparse 的命令行参数 - 如果参数无效,则会出现错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11540854/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com