Auto-reload turtle code on file save (https://docs.python.org/3/library/turtle.html)
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
"""Reloads the `my_turtle.py` code on save. | |
Put simple turtle instructions in the `my_turtle.py` file, | |
and they'll be re-run (on a clean window) on each file save. | |
Usage: | |
1/ put some turtle instructions in a `my_turtle.py` file | |
(eg `turtle.forward(100)`) | |
2/ run `python watch_turtle.py` on a commandline | |
(no dependencies needed) | |
3/ play around by adding/modifiying some turtle instructions | |
in the `my_turtle.py` file | |
4/ when you're happy with your modifications, save the file | |
(it'll empty the turtle screen and re-run the instructions) | |
5/ back to 3/ | |
Stop by pressing CTRL+C in the terminal. | |
""" | |
import os | |
import traceback | |
import sys | |
import time | |
import turtle | |
# Get the last modification time. Not as effective as some | |
# libs out there, but doesn't needs dependencies. | |
get_last_mod = lambda: os.stat('my_turtle.py').st_mtime | |
# Fancier than the original arrow shape. | |
turtle.shape('turtle') | |
# Initialize with a dummy value. | |
last_modification = 0 | |
while True: # Run until a KeyboardInterrupt (CTRL+C). | |
try: | |
if get_last_mod() != last_modification: | |
# Has the `my_turtle.py` file been saved? | |
print('Reloading...') | |
last_modification = get_last_mod() | |
# Empty the window, start from scratch. | |
turtle.reset() | |
# Re-run the instructions in the `my_turtle.py` file. | |
with open('my_turtle.py', 'r') as my_turtle: | |
exec(my_turtle.read()) | |
time.sleep(1) # Poll once a second. | |
except KeyboardInterrupt: # CTRL+C in the terminal. | |
print('Bye!') | |
sys.exit() | |
except: | |
# Anything wrong in the `my_turtle.py` file? | |
# Don't fail, just display the traceback, and continue. | |
print(traceback.format_exc()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment