Skip to content

Instantly share code, notes, and snippets.

@1337
Created May 12, 2014 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1337/e3360ceecead335eb0e8 to your computer and use it in GitHub Desktop.
Save 1337/e3360ceecead335eb0e8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
"""sudo cp xkcd.py /usr/local/bin/xkcd"""
__author__ = '1337'
from os.path import basename, join
from subprocess import call
import re
import sys
try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
IMAGE_PATH = '/tmp'
def get_image(url):
filename = basename(url)
filepath = join(IMAGE_PATH, filename)
with file(filepath, 'wb') as f:
f.write(urlopen(url).read())
f.close()
return filepath
def get_permalink(url):
page_contents = urlopen(url).read()
return re.findall(r'^\s*[a-zA-Z \(\)/]+:\s*([a-zA-Z0-9:/\.-_]+)\s*$',
page_contents, flags=re.U | re.M | re.I)[0]
if __name__ == '__main__':
if len(sys.argv) > 1:
url = "http://xkcd.com/{}".format(sys.argv[1])
else:
url = "http://xkcd.com"
filepath = get_image(get_permalink(url))
call(["display", filepath])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment