Python tornado.autoreload() Examples

The following are 19 code examples of tornado.autoreload(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado , or try the search function .
Example #1
Source File: autoreload.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def start(check_time: int = 500) -> None:
    """Begins watching source files for changes.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.
    """
    io_loop = ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    modify_times = {}  # type: Dict[str, float]
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time)
    scheduler.start() 
Example #2
Source File: autoreload.py    From teleport with Apache License 2.0 6 votes vote down vote up
def start(check_time=500):
    """Begins watching source files for changes.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.
    """
    io_loop = ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    modify_times = {}
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time)
    scheduler.start() 
Example #3
Source File: autoreload.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def start(check_time: int = 500) -> None:
    """Begins watching source files for changes.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.
    """
    io_loop = ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    modify_times = {}  # type: Dict[str, float]
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time)
    scheduler.start() 
Example #4
Source File: autoreload.py    From teleport with Apache License 2.0 6 votes vote down vote up
def start(check_time: int = 500) -> None:
    """Begins watching source files for changes.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.
    """
    io_loop = ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    modify_times = {}  # type: Dict[str, float]
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time)
    scheduler.start() 
Example #5
Source File: autoreload.py    From pySINDy with MIT License 6 votes vote down vote up
def start(check_time=500):
    """Begins watching source files for changes.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.
    """
    io_loop = ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    modify_times = {}
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time)
    scheduler.start() 
Example #6
Source File: guy.py    From guy with Apache License 2.0 6 votes vote down vote up
def __init__(self,instance,host="localhost",port=None,autoreload=False):
        super(WebServer, self).__init__()
        self.app=None
        self.instance=instance
        self.host=host
        self.autoreload=autoreload

        if port is not None:
            self.port = port

        while not isFree("localhost", self.port):
            self.port += 1

        self.instance._webserver=(self.host,self.port)

        try: # https://bugs.python.org/issue37373 FIX: tornado/py3.8 on windows
            if sys.platform == 'win32':
                asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
        except:
            pass 
Example #7
Source File: autoreload.py    From teleport with Apache License 2.0 5 votes vote down vote up
def start(check_time: int = 500) -> None:
    """Begins watching source files for changes.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.
    """
    io_loop = ioloop.IOLoop.current()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        gen_log.warning("tornado.autoreload started more than once in the same process")
    modify_times = {}  # type: Dict[str, float]
    callback = functools.partial(_reload_on_update, modify_times)
    scheduler = ioloop.PeriodicCallback(callback, check_time)
    scheduler.start() 
Example #8
Source File: guy.py    From guy with Apache License 2.0 5 votes vote down vote up
def serve(self,port=8000,log=False,open=True,autoreload=False):
        """ Run the guy's app for multiple clients (web/server mode) """
        self._log=log
        if log:
            handler.setLevel(logging.DEBUG)
            logger.setLevel(logging.DEBUG)

        ws=WebServer( self ,"0.0.0.0",port=port, autoreload=autoreload )
        ws.start()

        self.RETOUR=None
        def exit(v=None):
            self.RETOUR=v
            ws.exit()

        self._callbackExit = exit
        print("Running", ws.startPage )

        if open: #auto open browser
            try:
                import webbrowser
                webbrowser.open_new_tab(ws.startPage)
            except:
                pass

        try:
            ws.join() #important !
        except KeyboardInterrupt:
            print("-Process stopped")
        ws.exit()
        return self.RETOUR 
Example #9
Source File: guy.py    From guy with Apache License 2.0 5 votes vote down vote up
def runCef(self,log=False,autoreload=False,one=False):
        """ Run the guy's app in a windowed cefpython3 (one client)"""
        self._log=log
        if log:
            handler.setLevel(logging.DEBUG)
            logger.setLevel(logging.DEBUG)

        lockPort=None
        if one:
            lp=LockPortFile(self._name)
            if lp.bringToFront():
                return
            else:
                lockPort = lp.create()

        ws=WebServer( self, autoreload=autoreload )
        ws.start()

        self.RETOUR=None
        try:
            app=CefApp(ws.startPage,self.size,lockPort=lockPort)

            def cefexit(v=None):
                self.RETOUR=v
                app.exit()

            tornado.autoreload.add_reload_hook(app.exit)

            self._callbackExit = cefexit
            try:
                app.wait() # block
            except KeyboardInterrupt:
                print("-Process stopped")
        except Exception as e:
            print("Trouble with CEF:",e)
        ws.exit()
        ws.join()
        return self.RETOUR 
Example #10
Source File: testing.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        if (not IOLoop.initialized() or
            self.io_loop is not IOLoop.instance()):
            # Try to clean up any file descriptors left open in the ioloop.
            # This avoids leaks, especially when tests are run repeatedly
            # in the same process with autoreload (because curl does not
            # set FD_CLOEXEC on its file descriptors)
            self.io_loop.close(all_fds=True)
        super(AsyncTestCase, self).tearDown() 
Example #11
Source File: __init__.py    From pfrock with Apache License 2.0 5 votes vote down vote up
def __init__(self, auto_reload=True, port=8888):
        self.app = MyApplication(autoreload=True)
        self.auto_reload = auto_reload
        self.port = port
        logger.info("started server " + str(port) + (" with autoreload mode" if self.auto_reload else "")) 
Example #12
Source File: __init__.py    From pfrock with Apache License 2.0 5 votes vote down vote up
def add_watch(self, watch_file):
        tornado.autoreload.watch(watch_file) 
Example #13
Source File: guy.py    From guy with Apache License 2.0 5 votes vote down vote up
def run(self,log=False,autoreload=False,one=False,args=[]):
        """ Run the guy's app in a windowed env (one client)"""
        self._log=log
        if log:
            handler.setLevel(logging.DEBUG)
            logger.setLevel(logging.DEBUG)

        if ISANDROID: #TODO: add executable for kivy/iOs mac/apple
            runAndroid(self)
        else:
            lockPort=None
            if one:
                lp=LockPortFile(self._name)
                if lp.bringToFront():
                    return
                else:
                    lockPort = lp.create()

            ws=WebServer( self, autoreload=autoreload )
            ws.start()

            app=ChromeApp(ws.startPage,self._name,self.size,lockPort=lockPort,chromeargs=args)

            self.RETOUR=None
            def exit(v=None):
                self.RETOUR=v

                ws.exit()
                app.exit()

            tornado.autoreload.add_reload_hook(exit)

            self._callbackExit = exit
            try:
                app.wait() # block
            except KeyboardInterrupt:
                print("-Process stopped")

            ws.exit()
            ws.join()
            return self.RETOUR 
Example #14
Source File: autoreload.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
def _reload() -> None:
    global _reload_attempted
    _reload_attempted = True
    for fn in _reload_hooks:
        fn()
    if hasattr(signal, "setitimer"):
        # Clear the alarm signal set by
        # ioloop.set_blocking_log_threshold so it doesn't fire
        # after the exec.
        signal.setitimer(signal.ITIMER_REAL, 0, 0)
    # sys.path fixes: see comments at top of file.  If __main__.__spec__
    # exists, we were invoked with -m and the effective path is about to
    # change on re-exec.  Reconstruct the original command line to
    # ensure that the new process sees the same path we did.  If
    # __spec__ is not available (Python < 3.4), check instead if
    # sys.path[0] is an empty string and add the current directory to
    # $PYTHONPATH.
    if _autoreload_is_main:
        assert _original_argv is not None
        spec = _original_spec
        argv = _original_argv
    else:
        spec = getattr(sys.modules["__main__"], "__spec__", None)
        argv = sys.argv
    if spec:
        argv = ["-m", spec.name] + argv[1:]
    else:
        path_prefix = "." + os.pathsep
        if sys.path[0] == "" and not os.environ.get("PYTHONPATH", "").startswith(
            path_prefix
        ):
            os.environ["PYTHONPATH"] = path_prefix + os.environ.get("PYTHONPATH", "")
    if not _has_execv:
        subprocess.Popen([sys.executable] + argv)
        os._exit(0)
    else:
        try:
            os.execv(sys.executable, [sys.executable] + argv)
        except OSError:
            # Mac OS X versions prior to 10.6 do not support execv in
            # a process that contains multiple threads.  Instead of
            # re-executing in the current process, start a new one
            # and cause the current process to exit.  This isn't
            # ideal since the new process is detached from the parent
            # terminal and thus cannot easily be killed with ctrl-C,
            # but it's better than not being able to autoreload at
            # all.
            # Unfortunately the errno returned in this case does not
            # appear to be consistent, so we can't easily check for
            # this error specifically.
            os.spawnv(  # type: ignore
                os.P_NOWAIT, sys.executable, [sys.executable] + argv
            )
            # At this point the IOLoop has been closed and finally
            # blocks will experience errors if we allow the stack to
            # unwind, so just exit uncleanly.
            os._exit(0) 
Example #15
Source File: guy.py    From guy with Apache License 2.0 4 votes vote down vote up
def run(self):
        statics = os.path.join( self.instance._folder, FOLDERSTATIC)

        asyncio.set_event_loop(asyncio.new_event_loop())
        tornado.platform.asyncio.AsyncIOMainLoop().install()
        if self.autoreload:
            print("**AUTORELOAD**")
            tornado.autoreload.start()
            tornado.autoreload.watch( sys.argv[0] )
            if os.path.isdir(statics):
                for p in os.listdir( statics ) :
                    tornado.autoreload.watch(os.path.abspath(os.path.join(statics, p)))

        self.app=tornado.web.Application([
            (r'/_/(?P<url>.+)',             ProxyHandler,dict(instance=self.instance)),
            (r'/(?P<id>[^/]+)-ws',          WebSocketHandler,dict(instance=self.instance)),
            (r'/(?P<id>[^/]+)-js',          GuyJSHandler,dict(instance=self.instance)),
            (r'/(?P<page>[^\.]*)',          MainHandler,dict(instance=self.instance)),
            (r'/favicon.ico',               FavIconHandler,dict(instance=self.instance)),
            (r'/(.*)',                      tornado.web.StaticFileHandler, dict(path=statics ))
        ], compress_response=True)
        self.app.listen(self.port,address=self.host)

        self.loop=asyncio.get_event_loop()

        async def _waitExit():
            while self._exit==False:
                await asyncio.sleep(0.1)

        self._exit=False
        self.loop.run_until_complete(_waitExit())

        # gracefull death
        try:
            tasks = asyncio.all_tasks(self.loop) #py37
        except:
            tasks = asyncio.Task.all_tasks(self.loop) #py35
        for task in tasks: task.cancel()
        try:
            self.loop.run_until_complete(asyncio.gather(*tasks))
        except concurrent.futures._base.CancelledError:
            pass 
Example #16
Source File: autoreload.py    From pySINDy with MIT License 4 votes vote down vote up
def _reload():
    global _reload_attempted
    _reload_attempted = True
    for fn in _reload_hooks:
        fn()
    if hasattr(signal, "setitimer"):
        # Clear the alarm signal set by
        # ioloop.set_blocking_log_threshold so it doesn't fire
        # after the exec.
        signal.setitimer(signal.ITIMER_REAL, 0, 0)
    # sys.path fixes: see comments at top of file.  If __main__.__spec__
    # exists, we were invoked with -m and the effective path is about to
    # change on re-exec.  Reconstruct the original command line to
    # ensure that the new process sees the same path we did.  If
    # __spec__ is not available (Python < 3.4), check instead if
    # sys.path[0] is an empty string and add the current directory to
    # $PYTHONPATH.
    if _autoreload_is_main:
        spec = _original_spec
        argv = _original_argv
    else:
        spec = getattr(sys.modules['__main__'], '__spec__', None)
        argv = sys.argv
    if spec:
        argv = ['-m', spec.name] + argv[1:]
    else:
        path_prefix = '.' + os.pathsep
        if (sys.path[0] == '' and
                not os.environ.get("PYTHONPATH", "").startswith(path_prefix)):
            os.environ["PYTHONPATH"] = (path_prefix +
                                        os.environ.get("PYTHONPATH", ""))
    if not _has_execv:
        subprocess.Popen([sys.executable] + argv)
        os._exit(0)
    else:
        try:
            os.execv(sys.executable, [sys.executable] + argv)
        except OSError:
            # Mac OS X versions prior to 10.6 do not support execv in
            # a process that contains multiple threads.  Instead of
            # re-executing in the current process, start a new one
            # and cause the current process to exit.  This isn't
            # ideal since the new process is detached from the parent
            # terminal and thus cannot easily be killed with ctrl-C,
            # but it's better than not being able to autoreload at
            # all.
            # Unfortunately the errno returned in this case does not
            # appear to be consistent, so we can't easily check for
            # this error specifically.
            os.spawnv(os.P_NOWAIT, sys.executable, [sys.executable] + argv)
            # At this point the IOLoop has been closed and finally
            # blocks will experience errors if we allow the stack to
            # unwind, so just exit uncleanly.
            os._exit(0) 
Example #17
Source File: autoreload.py    From teleport with Apache License 2.0 4 votes vote down vote up
def _reload() -> None:
    global _reload_attempted
    _reload_attempted = True
    for fn in _reload_hooks:
        fn()
    if hasattr(signal, "setitimer"):
        # Clear the alarm signal set by
        # ioloop.set_blocking_log_threshold so it doesn't fire
        # after the exec.
        signal.setitimer(signal.ITIMER_REAL, 0, 0)
    # sys.path fixes: see comments at top of file.  If __main__.__spec__
    # exists, we were invoked with -m and the effective path is about to
    # change on re-exec.  Reconstruct the original command line to
    # ensure that the new process sees the same path we did.  If
    # __spec__ is not available (Python < 3.4), check instead if
    # sys.path[0] is an empty string and add the current directory to
    # $PYTHONPATH.
    if _autoreload_is_main:
        assert _original_argv is not None
        spec = _original_spec
        argv = _original_argv
    else:
        spec = getattr(sys.modules["__main__"], "__spec__", None)
        argv = sys.argv
    if spec:
        argv = ["-m", spec.name] + argv[1:]
    else:
        path_prefix = "." + os.pathsep
        if sys.path[0] == "" and not os.environ.get("PYTHONPATH", "").startswith(
            path_prefix
        ):
            os.environ["PYTHONPATH"] = path_prefix + os.environ.get("PYTHONPATH", "")
    if not _has_execv:
        subprocess.Popen([sys.executable] + argv)
        os._exit(0)
    else:
        try:
            os.execv(sys.executable, [sys.executable] + argv)
        except OSError:
            # Mac OS X versions prior to 10.6 do not support execv in
            # a process that contains multiple threads.  Instead of
            # re-executing in the current process, start a new one
            # and cause the current process to exit.  This isn't
            # ideal since the new process is detached from the parent
            # terminal and thus cannot easily be killed with ctrl-C,
            # but it's better than not being able to autoreload at
            # all.
            # Unfortunately the errno returned in this case does not
            # appear to be consistent, so we can't easily check for
            # this error specifically.
            os.spawnv(  # type: ignore
                os.P_NOWAIT, sys.executable, [sys.executable] + argv
            )
            # At this point the IOLoop has been closed and finally
            # blocks will experience errors if we allow the stack to
            # unwind, so just exit uncleanly.
            os._exit(0) 
Example #18
Source File: autoreload.py    From teleport with Apache License 2.0 4 votes vote down vote up
def _reload():
    global _reload_attempted
    _reload_attempted = True
    for fn in _reload_hooks:
        fn()
    if hasattr(signal, "setitimer"):
        # Clear the alarm signal set by
        # ioloop.set_blocking_log_threshold so it doesn't fire
        # after the exec.
        signal.setitimer(signal.ITIMER_REAL, 0, 0)
    # sys.path fixes: see comments at top of file.  If __main__.__spec__
    # exists, we were invoked with -m and the effective path is about to
    # change on re-exec.  Reconstruct the original command line to
    # ensure that the new process sees the same path we did.  If
    # __spec__ is not available (Python < 3.4), check instead if
    # sys.path[0] is an empty string and add the current directory to
    # $PYTHONPATH.
    if _autoreload_is_main:
        spec = _original_spec
        argv = _original_argv
    else:
        spec = getattr(sys.modules['__main__'], '__spec__', None)
        argv = sys.argv
    if spec:
        argv = ['-m', spec.name] + argv[1:]
    else:
        path_prefix = '.' + os.pathsep
        if (sys.path[0] == '' and
                not os.environ.get("PYTHONPATH", "").startswith(path_prefix)):
            os.environ["PYTHONPATH"] = (path_prefix +
                                        os.environ.get("PYTHONPATH", ""))
    if not _has_execv:
        subprocess.Popen([sys.executable] + argv)
        os._exit(0)
    else:
        try:
            os.execv(sys.executable, [sys.executable] + argv)
        except OSError:
            # Mac OS X versions prior to 10.6 do not support execv in
            # a process that contains multiple threads.  Instead of
            # re-executing in the current process, start a new one
            # and cause the current process to exit.  This isn't
            # ideal since the new process is detached from the parent
            # terminal and thus cannot easily be killed with ctrl-C,
            # but it's better than not being able to autoreload at
            # all.
            # Unfortunately the errno returned in this case does not
            # appear to be consistent, so we can't easily check for
            # this error specifically.
            os.spawnv(os.P_NOWAIT, sys.executable, [sys.executable] + argv)
            # At this point the IOLoop has been closed and finally
            # blocks will experience errors if we allow the stack to
            # unwind, so just exit uncleanly.
            os._exit(0) 
Example #19
Source File: autoreload.py    From opendevops with GNU General Public License v3.0 4 votes vote down vote up
def _reload() -> None:
    global _reload_attempted
    _reload_attempted = True
    for fn in _reload_hooks:
        fn()
    if hasattr(signal, "setitimer"):
        # Clear the alarm signal set by
        # ioloop.set_blocking_log_threshold so it doesn't fire
        # after the exec.
        signal.setitimer(signal.ITIMER_REAL, 0, 0)
    # sys.path fixes: see comments at top of file.  If __main__.__spec__
    # exists, we were invoked with -m and the effective path is about to
    # change on re-exec.  Reconstruct the original command line to
    # ensure that the new process sees the same path we did.  If
    # __spec__ is not available (Python < 3.4), check instead if
    # sys.path[0] is an empty string and add the current directory to
    # $PYTHONPATH.
    if _autoreload_is_main:
        assert _original_argv is not None
        spec = _original_spec
        argv = _original_argv
    else:
        spec = getattr(sys.modules["__main__"], "__spec__", None)
        argv = sys.argv
    if spec:
        argv = ["-m", spec.name] + argv[1:]
    else:
        path_prefix = "." + os.pathsep
        if sys.path[0] == "" and not os.environ.get("PYTHONPATH", "").startswith(
            path_prefix
        ):
            os.environ["PYTHONPATH"] = path_prefix + os.environ.get("PYTHONPATH", "")
    if not _has_execv:
        subprocess.Popen([sys.executable] + argv)
        os._exit(0)
    else:
        try:
            os.execv(sys.executable, [sys.executable] + argv)
        except OSError:
            # Mac OS X versions prior to 10.6 do not support execv in
            # a process that contains multiple threads.  Instead of
            # re-executing in the current process, start a new one
            # and cause the current process to exit.  This isn't
            # ideal since the new process is detached from the parent
            # terminal and thus cannot easily be killed with ctrl-C,
            # but it's better than not being able to autoreload at
            # all.
            # Unfortunately the errno returned in this case does not
            # appear to be consistent, so we can't easily check for
            # this error specifically.
            os.spawnv(  # type: ignore
                os.P_NOWAIT, sys.executable, [sys.executable] + argv
            )
            # At this point the IOLoop has been closed and finally
            # blocks will experience errors if we allow the stack to
            # unwind, so just exit uncleanly.
            os._exit(0)