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

前端 未结 3 1866
夕颜
夕颜 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:10

    I have just found this one:

    def extant_file(x):
        """
        'Type' for argparse - checks that file exists but does not open.
        """
        if not os.path.exists(x):
            # Argparse uses the ArgumentTypeError to give a rejection message like:
            # error: argument input: x does not exist
            raise argparse.ArgumentTypeError("{0} does not exist".format(x))
        return x
    
    if __name__ == "__main__":
        import argparse, sys, os
        from argparse import ArgumentParser
    
        parser = ArgumentParser(description="ikjMatrix multiplication")
        parser.add_argument("-i", "--input",
            dest="filename", required=True, type=extant_file,
            help="input file with two matrices", metavar="FILE")
        args = parser.parse_args()
    
        A, B = read(args.filename)
        C = ikjMatrixProduct(A, B)
        printMatrix(C, args.output)
    

    Source: fhcrc.github.com

提交回复
热议问题