Skip to content

Instantly share code, notes, and snippets.

@Phaqui
Created April 8, 2019 18:15
Show Gist options
  • Save Phaqui/ab4f4f0537c033c5b8891cdc39d9b30e to your computer and use it in GitHub Desktop.
Save Phaqui/ab4f4f0537c033c5b8891cdc39d9b30e to your computer and use it in GitHub Desktop.
live reloading of small python scripts
"""
livereload.py - quick "hot reloading" of small python scripts
demo video: https://imgur.com/a/fLbfHIG
"""
import sys
import os
import time
import traceback
def run(fname, mtime=-1):
newmtime = os.stat(fname)
if newmtime == mtime:
return mtime
os.system('clear')
print(f'livereload.py: {fname}\n===========================')
with open(fname) as f:
source = f.read()
try:
code = compile(source, fname, 'exec')
except (ValueError, SyntaxError) as e:
traceback.print_exception(type(e), e, None, file=sys.stdout)
else:
d = dict()
try:
exec(code, d, d)
except Exception as e:
tb = sys.exc_info()[2]
l = traceback.format_tb(tb)
print("Traceback (most recent call last):")
print(*l[1:], end='')
print(e.__class__.__name__ + ": " + str(e))
finally:
return newmtime
def mainloop(fname, delay):
mtime = -1
while True:
mtime = run(fname, mtime)
try:
time.sleep(delay)
except KeyboardInterrupt:
break
def main():
usage = "usage: livereload.py <filename> [delay=0.5]"
fname = sys.argv[1] if len(sys.argv) > 1 else sys.exit(usage)
delay = sys.argv[2] if len(sys.argv) == 3 else 0.5
mainloop(fname, delay)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment