updater.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. '''
  2. Auto-updater
  3. '''
  4. from distutils.version import StrictVersion
  5. import os
  6. from subprocess import Popen
  7. import sys
  8. import tempfile
  9. import requests
  10. VERSIONFILE_URL = "http://codebox/lab/ModelePython/raw/master/VERSION"
  11. SETUPFILE_URL = "http://codebox/lab/ModelePython/raw/master/setup-hello_world.exe"
  12. CURDIR = os.path.dirname(__file__)
  13. TMPDIR = os.path.join(tempfile.gettempdir(), os.path.basename(CURDIR), "update")
  14. TMP_SETUPFILE = os.path.join(TMPDIR, "setup.exe")
  15. class UpdateNeeded(Exception):
  16. pass
  17. class Unavailable(requests.exceptions.RequestException):
  18. pass
  19. def autoupdate():
  20. clean_old()
  21. try:
  22. if update_needed():
  23. update()
  24. except Unavailable:
  25. pass
  26. def clean_old():
  27. try:
  28. os.rmdir(TMPDIR)
  29. except:
  30. pass
  31. def update_needed():
  32. # Available version
  33. try:
  34. raw = requests.get(VERSIONFILE_URL).text
  35. available_version = StrictVersion(raw)
  36. except (ValueError, requests.exceptions.RequestException):
  37. raise Unavailable()
  38. # Installed version
  39. with open(os.path.join(CURDIR, "VERSION")) as f:
  40. installed_version = f.read()
  41. return available_version > installed_version
  42. def update():
  43. # Download the setup.exe
  44. response = requests.get(SETUPFILE_URL, stream=True)
  45. os.mkdir(TMPDIR)
  46. with open(TMP_SETUPFILE, "wb") as handle:
  47. for chunk in response.iter_content(chunk_size=1024):
  48. if chunk:
  49. handle.write(chunk)
  50. # Run the installer and restart the start command
  51. args = "/c {} /SILENT & {} {}".format(TMP_SETUPFILE, sys.executable, " ".join(sys.argv[:]))
  52. Popen(["cmd.exe", args], shell=True)
  53. # An UpdateNeeded exception is raised so the script exit before being restarted by subprocess
  54. raise UpdateNeeded()