Skip to content

Instantly share code, notes, and snippets.

@craigdub
Last active December 28, 2015 17:58
Show Gist options
  • Save craigdub/7539139 to your computer and use it in GitHub Desktop.
Save craigdub/7539139 to your computer and use it in GitHub Desktop.
Install sublime with python
import urllib2
import re
import os
import sys
import shutil
from BeautifulSoup import BeautifulSoup
import subprocess as sp
SUBLIME_BASE = 'http://www.sublimetext.com/'
SUBLIME_VERSION = 2
def sublime_install(base, version):
# Sublime text .dmg dl url
img_url = sublime_fetch_img_url(base, version)
# Dl dmg
dl_dest_pth = os.path.expanduser('~') + '/' + 'sublime%s.dmg' % version
dmg = dl_img(img_url, dl_dest_pth)
# Mount
tmp_mnt = '/tmp/sublime_text.123'
if os.path.exists(tmp_mnt) is False:
os.mkdir(tmp_mnt)
cmd = ['hdiutil', 'attach', dmg.name, '-mountpoint', tmp_mnt]
print('Mounting sublime image:' + tmp_mnt)
try:
print(sp.check_output(' '.join(cmd), shell=True))
except sp.CalledProcessError:
pass
# Find the app file
apps_pth = os.path.expanduser('~') + '/Applications'
# Copy app to ~/Applications
for f in os.listdir(tmp_mnt):
if re.search('\.app', f):
sublime_app_file = tmp_mnt + '/' + f
if os.path.exists(sublime_app_file) is False:
print('Copying ' + sublime_app_file + ' -> ' + apps_pth)
# TODO: change home dir to apps_pth
shutil.copytree(sublime_app_file, apps_pth + '/' + f)
else:
print apps_pth + '/' + f + ' exists!'
# Detach
cmd = ['hdiutil', 'detach', tmp_mnt]
try:
print(sp.check_output(' '.join(cmd), shell=True))
except sp.CalledProcessError:
pass
def sublime_fetch_img_url(base, version):
html = urllib2.urlopen(base + str(version)).read()
soup = BeautifulSoup(html)
lnk = soup.find(id=re.compile("dl_osx")).find('a')
img_url = lnk['href'].replace('http://', '')
img_url = 'http://' + urllib2.quote(img_url)
return img_url
def dl_img(src, dest):
with open(dest, 'w') as f:
dmg = urllib2.urlopen(src)
meta = dmg.info()
file_size = int(meta.getheaders("Content-Length")[0])
file_size_dl = 0
block_sz = 8192
while True:
buffer = dmg.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"\r%10d [%3.2f%%]" % (file_size_dl,
file_size_dl * 100. / file_size)
sys.stdout.write('\rProgress %s' % (status))
print('\n')
return f
if __name__ == '__main__':
sublime_install(SUBLIME_BASE, SUBLIME_VERSION)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment