Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from code import InteractiveConsole
- from os.path import getmtime, basename
- from datetime import datetime
- import sys
- class AutoReloader(InteractiveConsole):
- watch_pkg = None
- last_load_time = None
- def __init__(self, locals=None, filename="<console>", watch_pkg=None, watch_file=None):
- super().__init__(locals=locals, filename=filename)
- if watch_file is not None and watch_file.endswith('.py'):
- watch_pkg = watch_file.split('.')[0]
- if watch_pkg is not None:
- self.watch_pkg = watch_pkg
- self.runcode('import {0}'.format(self.watch_pkg)) # Necessary to be able to reload the funcs
- self.runcode('from {0} import *'.format(self.watch_pkg))
- self.last_load_time = datetime.utcnow()
- self.runcode('from importlib import reload')
- def runsource(self, source, filename="<input>", symbol="single"):
- if self.watch_pkg is not None and self.was_modified():
- self.runcode('reload({0})'.format(self.watch_pkg)) # Reload function definitions...
- self.runcode('from {0} import *'.format(self.watch_pkg)) # ...and pull them into interpreter namespace.
- return super().runsource(source, filename=filename, symbol=symbol)
- def was_modified(self):
- if self.last_load_time is None:
- return False
- try:
- modtime = datetime.utcfromtimestamp(getmtime('{0}.py'.format(self.watch_pkg)))
- if modtime > self.last_load_time:
- self.last_load_time = datetime.utcnow()
- return True
- else:
- return False
- except:
- print('Could not find file {0} to reload package {1}. Disabling reload.'.format('{0}.py'.format(self.watch_pkg), self.watch_pkg))
- self.watch_pkg = None
- self.last_load_time = None
- return False
- def showtraceback(self):
- type, value, tb = sys.exc_info()
- if type == ImportError and value.name == self.watch_pkg:
- print('Loading package {0} failed.'.format(self.watch_pkg))
- self.watch_pkg = None
- self.last_load_time = None
- else:
- return super().showtraceback()
- def interact(self):
- banner = None
- if self.watch_pkg is not None:
- banner = 'AutoReloading interpreter loaded watching package: {0}'.format(self.watch_pkg)
- else:
- banner = 'AutoReloading interpreter loaded without a package to watch'
- return super().interact(banner=banner)
- @staticmethod
- def run_console():
- from inspect import stack, getmodule
- frame = stack()[1]
- module = getmodule(frame[0])
- AutoReloader(watch_file=basename(module.__file__)).interact()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement