我遵循这个建议: File as command line argument for argparse - error message if argument is not valid 打印文件的内容。这是一个MWE:
import argparse
import os
def is_valid_file(parser, arg):
"""
:rtype : open file handle
"""
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 = argparse.ArgumentParser(description='do shit')
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()
print(args.filename.read)
但是,我得到的不是文件内容:
<built-in method read of _io.TextIOWrapper object at 0x7f1988b3bb40>
我做错了什么?
答案 0 :(得分:5)