Skip to content

Instantly share code, notes, and snippets.

@davidbgk
Forked from magopian/watch_turtle.py
Last active September 18, 2023 23:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidbgk/21aefce3f26423034f0f to your computer and use it in GitHub Desktop.
Save davidbgk/21aefce3f26423034f0f to your computer and use it in GitHub Desktop.
Auto-reload turtle code on file save (https://docs.python.org/3/library/turtle.html)
"""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