1+ ###############################################################################
2+ #
3+ # File: store_images.py
4+ #
5+ # Author: Isaac Ingram
6+ #
7+ # Purpose: Store an image stream from a website to the local disk.
8+ #
9+ # Usage: This program requires the requests library to be installed.
10+ # To use, provide two commandline arguments: <URL> and <path>. 'URL' is the URL
11+ # to requests content from. 'path' is the relative or absolute path to where
12+ # the images should be placed on your system.
13+ #
14+ ###############################################################################
15+ import sys
16+ from datetime import datetime
17+
18+ import requests
19+
20+
21+ def print_usage_and_exit () -> None :
22+ """
23+ Print the usage statement and exit.
24+ :return: None
25+ """
26+ print ("Usage: store_images.py <URL> <path>" )
27+ exit (0 )
28+
29+
30+ def main ():
31+ try :
32+ while (True ):
33+ # Check command line args
34+ if len (sys .argv ) != 3 :
35+ print_usage_and_exit ()
36+ url = sys .argv [1 ]
37+ storage_path = sys .argv [2 ]
38+ # Get rid of last character in path if it's a slash
39+ if storage_path [- 1 ] == "/" :
40+ storage_path = storage_path [:- 1 ]
41+ try :
42+ image_data = requests .get (url ).content
43+ img_name = f'{ storage_path } /{ datetime .now ().strftime ("%S-%M-%H-%d-%m-%Y.jpg" )} '
44+ with open (img_name , 'wb' ) as image_file :
45+ image_file .write (image_data )
46+ except Exception as e :
47+ print (f"Failed to download from { url } : { e } " )
48+ except KeyboardInterrupt :
49+ print ("Program interrupted by user. Exiting..." )
50+
51+
52+ if __name__ == '__main__' :
53+ main ()
0 commit comments