diff --git a/asciify.py b/asciify.py index 2463731..91c1b34 100644 --- a/asciify.py +++ b/asciify.py @@ -54,12 +54,12 @@ def do(image, new_width=100): - handles exceptions as well - provides alternative output options ''' -def runner(path): +def runner(img_path, save_path): image = None try: - image = Image.open(path) + image = Image.open(img_path) except Exception: - print("Unable to find image in",path) + print("Unable to find image in", img_path) #print(e) return image = do(image) @@ -71,9 +71,17 @@ def runner(path): # Note: This text file will be created by default under # the same directory as this python file, # NOT in the directory from where the image is pulled. - f = open('img.txt','w') - f.write(image) - f.close() + try: + with open(save_path, 'w') as f: + f.write(image) + except FileNotFoundError: + print(f"\nNo such directory to save output to: {save_path}") + print("Check for typos/mistakes or create the directories beforehand") + return + except PermissionError: + print(f"\nPermission error when saving output to {save_path}") + print("Ensure that sufficient permissions are given, or that a folder does not have the same name") + return ''' method main(): @@ -83,9 +91,34 @@ def runner(path): if __name__ == '__main__': import sys import urllib.request + import urllib.error + import os + + # No arguments given + if len(sys.argv) == 1: + print("Relative/absolute path or URL of image must be provided") + print("usage: python asciify.py [save_location]") + sys.exit() + + # Find name of image file + img_name = sys.argv[1][sys.argv[1].rfind("/") + 1:sys.argv[1].rfind(".")] + if sys.argv[1].startswith('http://') or sys.argv[1].startswith('https://'): - urllib.request.urlretrieve(sys.argv[1], "asciify.jpg") - path = "asciify.jpg" + try: + urllib.request.urlretrieve(sys.argv[1], img_name + ".jpg") + except urllib.error.HTTPError: + print("Invalid URL:", sys.argv[1]) + sys.exit() + img_path = img_name + ".jpg" else: - path = sys.argv[1] - runner(path) + img_path = sys.argv[1] + + if len(sys.argv) > 2: + if sys.argv[2].endswith(".txt"): + save_path = sys.argv[2] + else: + save_path = sys.argv[2] + os.path.sep + img_name + "-asciified.txt" + else: + save_path = img_name + "-asciified.txt" + + runner(img_path, save_path)