Reputation: 718
I'm using argparse
for passing to my script two different arguments (they are actually two files: an image and a json file) and use them for initialize my instance. And this works. But what if I would like to handle the case in which I pass the wrong number of arguments (less than two) or maybe the two arguments - the two files - doesn't exist?
parser = argparse.ArgumentParser(description='MyAgonism')
parser.add_argument('image')
parser.add_argument('json')
args = parser.parse_args()
MyAgonism = board(args.json, args.image)
Upvotes: 0
Views: 1700
Reputation: 31905
You can check the numbers of arguments, and then check whether files exist.
def validate_num_of_args(args):
return True if len(vars(args)) == 2 else False
def validate_image_arg(imagearg):
has_found_image = True if os.path.exists(imagearg) else False
has_valid_name = True if imagearg.endswith("jpeg") or imagearg.endswith("png") else False
return has_found_image and has_valid_name
def validate_json_arg(jsonarg):
...
...
def validate_args(args):
if validate_num_of_args(args):
jsonarg, imagearg = args.json, args.image
if validate_json_arg(jsonarg) and validate_image_arg(imagearg):
pass
# do your thing
else:
print "Error, invalid json/images files"
else:
print "Error, invalid number of arguments"
If your json and image files have naming conventions, you can also check the file names, like checking the files startswith()
specific prefix, and endswith()
specific suffix and so on.
Upvotes: 1
Reputation: 231510
As written the parser
will complain if you don't give it 2 arguments. Try it!
As for checking that the arguments are valid - files exist, can be opened, etc - normal Python error checking and messages can be used. argparse
is a parser, not a complete programming script.
Upvotes: 1