File as command line argument for argparse - error message if argument is not valid

前端 未结 3 1865
夕颜
夕颜 2021-02-01 00:50

I am currently using argparse like this:

import argparse
from argparse import ArgumentParser

parser = ArgumentParser(description=\"ikjMatrix multiplication\")
p         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 01:02

    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)
    

提交回复
热议问题