def check_file(user_name,default_name):
while True:
try:
#### check user name matches the default name
if ('%s'%(user_name)) == '%s'%(default_name):
print("file matches")
break
except:
print("wrong file.")
continue
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-k1',type=argparse.FileType('r'),default='k1file.txt',required=True,
help='file input')
parser.add_argument('-k2',type=argparse.FileType('r'),default='k2file.txt',required=True,
help='file input')
args = parser.parse_args()
check_file(args.k1,args.get_default('k1'))
check_file(args.k2,args.get_default('k2'))
Present output:
AttributeError: 'Namespace' object has no attribute 'k1'
print(args), so you see what the parser has done, without any further assumptions or processing. Off hand it looks like it should have ak1attribute, but I'd like to see the print to be sure. What's thatargs.get_default('k1')supposed to do? It doesn't look right.argsnamespace object does not have access to thedefault. That's an attribute of theActionobject created byadd_argument. Why are you expecting the user to enter the same thing as the default? Just to make them jump-through-some-hoops? Whyrequiredis True?defaultis a string. But with thattype, the value inargswill be an opened file. They won't be equal. That's yet another reason to print theargs, to check on the value as well as name. When new to a module, be careful about your assumptions.typeand just accept a filename string. You can open it later in awithcontext if it is right.