Created
September 18, 2018 03:44
-
-
Save janglapuk/6425bf7ea8e7e65d97aadd101a2fad20 to your computer and use it in GitHub Desktop.
Simple Python autoreload script
This file contains hidden or 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
import os, sys, subprocess, signal, binascii, time | |
""" | |
Usage: | |
$ python autoreload.py app.py | |
""" | |
last_crc32 = 0 | |
terminate = False | |
def signal_handler(signum, frame): | |
global terminate | |
terminate = True | |
print('CTRL+C has interrupt auto reloading') | |
def main(): | |
if len(sys.argv) != 2: | |
print('Please pass an script argument!') | |
exit(-1) | |
script = sys.argv[1] | |
if not os.path.isfile(script): | |
print('Script file is not a file or exist') | |
exit(-2) | |
global last_crc32, terminate | |
process = None | |
while not terminate: | |
script_content = open(script).read().encode() | |
current_crc32 = binascii.crc32(script_content) | |
if last_crc32 != current_crc32: | |
last_crc32 = current_crc32 | |
if process is not None: | |
pid = process.pid | |
print('Killing PID:', pid) | |
os.kill(pid, signal.SIGINT) | |
process = None | |
print('Auto reloading script: ', script) | |
process = subprocess.Popen(['python', script], shell=False) | |
print('Reloaded on PID:', process.pid) | |
time.sleep(1.0) | |
if process is not None: | |
os.kill(process.pid, signal.SIGINT) | |
print('Exiting ...') | |
sys.exit(0) | |
if __name__ == '__main__': | |
signal.signal(signal.SIGINT, signal_handler) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment