参数-i应该是2个可读文件。

问题描述 投票:0回答:1

我目前使用的argparse是这样的。

from argparse import ArgumentParser

def is_valid_file(parser, arg):
    if not os.path.exists(arg):
        parser.error("File %s khong ton tai!" % arg)
    else:
        return open(arg, 'rb')   # return an open file handle

def readinput():
    parser = ArgumentParser(description="ikjMatrix multiplication")
    parser.add_argument("-i", dest="filename", required=True,
                        help="File need predict", metavar="FILE",
                        type=lambda x: is_valid_file(parser, x))
    args = parser.parse_args()
    return args.filename.read()

我想运行python3 demo.py -i text1. txt text2. txt.

我想得到两个可读文件。我如何才能做到这一点?

谢谢你的帮助

python argparse
1个回答
0
投票
import argparse

parser = argparse.ArgumentParser(description="Testfile")
parser.add_argument("-f", "--files", help="The files", nargs=2)
args = parser.parse_args()
print(args.files)

用法:

python .\test.py -f 1.txt 2.txt
['1.txt', '2.txt']

python .\test.py -f 1.txt      
usage: test.py [-h] [-f FILES FILES]
test.py: error: argument -f/--files: expected 2 arguments
© www.soinside.com 2019 - 2024. All rights reserved.