Created
July 12, 2012 17:29
-
-
Save TkTech/3099505 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import with_statement | |
import os | |
import sys | |
import random | |
import getopt | |
import string | |
from itertools import repeat | |
from urllib2 import Request, urlopen, URLError, HTTPError | |
def rand_string(string_length): | |
return ''.join(random.choice( | |
string.ascii_letters + string.digits) for i in range(string_length)) | |
def get_images(count=5, output='output'): | |
if not os.path.exists(output): | |
os.makedirs(output) | |
for n in repeat(None, count): | |
good = False | |
while not good: | |
img_name = rand_string(5) | |
img_path = os.path.join(output, '{0}.jpg'.format(img_name)) | |
url = "http://i.imgur.com/{0}.jpg".format(img_name) | |
req = Request(url) | |
try: | |
f = urlopen(req) | |
print("Downloading {0}".format(url)) | |
with open(img_path, "wb") as local_file: | |
local_file.write(f.read()) | |
good = True | |
except HTTPError, e: | |
print("HTTP Error: {0!r} URL: {1}".format(e.code, url)) | |
print('Trying again...') | |
except URLError, e: | |
print("URL Error: {0!r} URL: {1}".format(e.reason, url)) | |
print('Trying again...') | |
def main(argv): | |
try: | |
opts, args = getopt.gnu_getopt(argv[1:], '', [ | |
'output=', | |
'count=' | |
]) | |
except getopt.GetoptError, e: | |
print(str(e)) | |
return 1 | |
output = 'output' | |
count = 5 | |
for o, a in opts: | |
if o == '--output': | |
output = a | |
elif o == '--count': | |
try: | |
count = int(a) | |
except ValueError, e: | |
print(str(e)) | |
return 1 | |
else: | |
print('Unrecognized option {0}'.format(o)) | |
return 1 | |
get_images(count=count, output=output) | |
if __name__ == '__main__': | |
sys.exit(main(sys.argv)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment