Exemple #1
0
def main(channelname = None):
    app = QApplication(sys.argv)
    app.setOrganizationName("NSLS II")
    app.setOrganizationDomain("BNL")
    app.setApplicationName("MASAR Viewer")
    if channelname:
        form = masarUI(channelname=channelname)
    else:
        form = masarUI()
    form.show()
    app.exec_()
    
    import atexit
    # clean Python local objects first, especially the cothread stuff.
    # Cothread adds a new function in catools._catools_atexit(), ca_flush_io(), since version 2.8
    # to flush all io and do a clean up. This function registered at Python exit, and will be called 
    # by Python exit handler.
    # This forces the clean up has be done before calling epicsExit(). 
    atexit._run_exitfuncs()

    # it is safe to clean epics objects now.
    epicsExit()
    
    # call os.exit() instead of sys.exit()
    # os._exit(0)
    # however, os._exit() does nothing when exiting.
    # It would be better to call sys.exit
    sys.exit()
                def hardExit():
                    # run all the other exit handlers registered with
                    # atexit, then hard exit... this is easy, because
                    # atexit._run_exitfuncs pops funcs off the stack as it goes...
                    # so all we need to do is call it again
                    import sys
                    atexit._run_exitfuncs()
                    try:
                        print "pymel: hard exiting to avoid mayapy crash..."
                    except Exception:
                        pass
                    import os
                    import sys

                    exitStatus = getattr(sys, '_exit_status', None)
                    if exitStatus is None:
                        last_value = getattr(sys, 'last_value', None)
                        if last_value is not None:
                            if isinstance(last_value, SystemExit):
                                try:
                                    exitStatus = last_value.args[0]
                                except Exception:
                                    pass
                            if exitStatus is None:
                                exitStatus = 1
                    if exitStatus is None:
                        exitStatus = 0
                    os._exit(exitStatus)
Exemple #3
0
def _pyxcel_cmdline(argv=''):
    """run a python script or module if we have leading -m"""
    try:
        argv = eval(argv)

        if argv[0] == '-c':
            sys.argv = [argv[0]] + argv[2:]
            print 'i got ', sys.argv
            exec(argv[1], vars(sys.modules['__main__']))
        elif argv[0] == '-m':
            sys.argv = [__file__] + argv[2:]
            # run module seems to overwrite [0] with '', so put a dummy
            # entry in to avoid that.
            sys.path = ['<dummy> '] + sys.path
            runpy.run_module(argv[1], run_name='__main__')
        else:
            sys.argv = [__file__] + argv[1:]
            runpy.run_path(argv[0], run_name='__main__')
        return 0
    except SystemExit as e:
        return e.code
    except:
        sys.excepthook(*sys.exc_info())
        return 1
    finally:
        # fake a call to atexit
        atexit._run_exitfuncs()
Exemple #4
0
def exit():
    """
    Causes python to exit without garbage-collecting any objects, and thus avoids
    calling object destructor methods. This is a sledgehammer workaround for 
    a variety of bugs in PyQt and Pyside that cause crashes on exit.
    
    This function does the following in an attempt to 'safely' terminate
    the process:
    
    * Invoke atexit callbacks
    * Close all open file handles
    * os._exit()
    
    Note: there is some potential for causing damage with this function if you
    are using objects that _require_ their destructors to be called (for example,
    to properly terminate log files, disconnect from devices, etc). Situations
    like this are probably quite rare, but use at your own risk.
    """

    ## first disable our own cleanup function; won't be needing it.
    setConfigOptions(exitCleanup=False)

    ## invoke atexit callbacks
    atexit._run_exitfuncs()

    ## close file handles
    os.closerange(3, 4096)  ## just guessing on the maximum descriptor count..

    os._exit(0)
Exemple #5
0
def _predictor_server(path, qi, qo):
    # Using os.fork() (called from multiprocessing) and allowing cleanups to be run like
    # normal is dangerous because some filesystem-related cleanups might be called
    # twice. That's why we remove them first, without executing them in this process.
    atexit._clear()

    from allennlp.predictors.predictor import Predictor
    from allennlp.predictors.semantic_role_labeler import SemanticRoleLabelerPredictor
    from allennlp.data.tokenizers.word_splitter import SpacyWordSplitter

    # Use en_core_web_md for tokenizer instead
    # TODO: make optional
    SemanticRoleLabelerPredictor.__init__ = Predictor.__init__

    predictor = Predictor.from_path(path)
    predictor._tokenizer = SpacyWordSplitter(language="en_core_web_md",
                                             pos_tags=True)
    while True:
        s = qi.get()
        if s is None:
            break
        qo.put_nowait(predictor.predict(s))

    # We need to manually call atexit callbacks here because the multiprocessing module
    # doesn't call them:
    # https://stackoverflow.com/a/34507557/
    # https://github.com/python/cpython/blob/49fd6dd887df6ea18dbb1a3c0f599239ccd1cb42/Lib/multiprocessing/popen_fork.py#L75
    # But if we don't call them, allennlp leaves extracted archives in the $TMPDIR:
    # https://github.com/allenai/allennlp/blob/fefc439035df87e3d2484eb2f53ca921c4c2e2fe/allennlp/models/archival.py#L176-L178
    logger.debug("atexit should call %d callbacks", atexit._ncallbacks())
    atexit._run_exitfuncs()
    def test_atexit_with_multiple_clients(self):
        """Test that each client has a separate atexit function"""
        config1 = copy.deepcopy(config)
        config2 = copy.deepcopy(config)
        config2["name"] = "cloned"
        with create_experiment(exp_config=config1,
                               trial_config=base_trial) as (
                                   _,
                                   _,
                                   client1,
                               ):
            with create_experiment(exp_config=config2,
                                   trial_config=base_trial) as (
                                       _,
                                       _,
                                       client2,
                                   ):
                trial1 = client1.suggest()
                trial2 = client2.suggest()

                assert trial1.status == "reserved"
                assert trial2.status == "reserved"

                atexit._run_exitfuncs()

                assert client1._pacemakers == {}
                assert client2._pacemakers == {}
                assert client1.get_trial(trial1).status == "broken"
                assert client2.get_trial(trial2).status == "broken"
Exemple #7
0
 def _run_atexit_funcs(self):
     """
     Newer Ansibles use atexit.register() to trigger tmpdir cleanup, when
     AnsibleModule.tmpdir is responsible for creating its own temporary
     directory.
     """
     atexit._run_exitfuncs()
    def test_atexit_with_multiple_clients_unregister(self, monkeypatch):
        """Test that each client has a separate atexit function that can be unregistered"""
        config1 = copy.deepcopy(config)
        config2 = copy.deepcopy(config)
        config2['name'] = 'cloned'
        with create_experiment(exp_config=config1) as (_, _, client1):

            def please_dont_call_me(client):
                raise RuntimeError("Please don't call me!!!")

            monkeypatch.setattr('orion.client.experiment.set_broken_trials', please_dont_call_me)

            with create_experiment(exp_config=config2) as (_, _, client2):
                trial1 = client1.suggest()
                trial2 = client2.suggest()

                # The registered function in atexit is called as expected
                with pytest.raises(RuntimeError) as exc:
                    atexit._run_exitfuncs()

                assert "Please don't call me!!!" == str(exc.value)

                # Unregister the function
                client2.release(trial2)
                client2.close()

                # It should not be called
                atexit._run_exitfuncs()

                assert client1._pacemakers == {}
                assert client2._pacemakers == {}
                assert client1.get_trial(trial1).status == 'broken'
                assert client2.get_trial(trial2).status == 'interrupted'
Exemple #9
0
    def test_setup_startup_and_shutdown_shutdown_callable(self):
        def func():
            raise AtExitTestException()

        self.config.call_on_shutdown = [func]
        self.config.setup_startup_and_shutdown()
        atexit._run_exitfuncs()
Exemple #10
0
                def hardExit():
                    # run all the other exit handlers registered with
                    # atexit, then hard exit... this is easy, because
                    # atexit._run_exitfuncs pops funcs off the stack as it goes...
                    # so all we need to do is call it again
                    import sys
                    atexit._run_exitfuncs()
                    try:
                        print "pymel: hard exiting to avoid mayapy crash..."
                    except Exception:
                        pass
                    import os
                    import sys

                    exitStatus = getattr(sys, '_exit_status', None)
                    if exitStatus is None:
                        last_value = getattr(sys, 'last_value', None)
                        if last_value is not None:
                            if isinstance(last_value, SystemExit):
                                try:
                                    exitStatus = last_value.args[0]
                                except Exception: pass
                            if exitStatus is None:
                                exitStatus = 1
                    if exitStatus is None:
                        exitStatus = 0
                    os._exit(exitStatus)
 def on_restart(self):
     if self._engine is not None:
         self._engine.restart()
     else:
         atexit._run_exitfuncs()
         args = [sys.executable, '-m', __spec__.name]
         os.execv(args[0], args)
Exemple #12
0
 def test_args(self):
     atexit.register(self.h1)
     atexit.register(self.h4)
     atexit.register(self.h4, 4, kw="abc")
     atexit._run_exitfuncs()
     self.assertEqual(self.subst_io.getvalue(),
                      "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n")
Exemple #13
0
    def test_setup_startup_and_shutdown_shutdown_callable(self):
        def func():
            raise AtExitTestException()

        self.config.call_on_shutdown = [func]
        self.config._setup_startup_and_shutdown()
        atexit._run_exitfuncs()
 def test_args(self):
     atexit.register(h1)
     atexit.register(h4)
     atexit.register(h4, 4, kw='abc')
     atexit._run_exitfuncs()
     self.assertEqual(self.stream.getvalue(),
                      "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n")
    def run(self, cmd, globalsDict=None, localsDict=None, debug=True):
        """Starts a given command under debugger control"""
        if globalsDict is None:
            import __main__
            globalsDict = __main__.__dict__

        if localsDict is None:
            localsDict = globalsDict

        if not isinstance(cmd, types.CodeType):
            cmd = compile(cmd, "<string>", "exec")

        if debug:
            # First time the trace_dispatch function is called, a "base debug"
            # function has to be returned, which is called at every user code
            # function call. This is ensured by setting stop_everywhere.
            self.stop_everywhere = True
            sys.settrace(self.trace_dispatch)

        try:
            exec(cmd, globalsDict, localsDict)
            atexit._run_exitfuncs()
            self._dbgClient.progTerminated(0)
        except SystemExit:
            atexit._run_exitfuncs()
            excinfo = sys.exc_info()
            exitcode, message = self.__extractSystemExitMessage(excinfo)
            self._dbgClient.progTerminated(exitcode, message)
        except Exception:
            excinfo = sys.exc_info()
            self.user_exception(excinfo, True)
        finally:
            self.quitting = True
            sys.settrace(None)
 def test_args(self):
     atexit.register(self.h1)
     atexit.register(self.h4)
     atexit.register(self.h4, 4, kw="abc")
     atexit._run_exitfuncs()
     self.assertEqual(self.subst_io.getvalue(),
                      "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n")
Exemple #17
0
    def run(self):
        import os
        import viztracer
        import signal
        import atexit

        def exit_routine() -> None:
            tracer = viztracer.get_tracer()
            if tracer is not None:
                tracer.stop()
                atexit.unregister(exit_routine)
                if not self._exiting:
                    self._exiting = True
                    tracer.save()
                    tracer.terminate()
                    exit(0)

        def term_handler(signalnum, frame):
            exit_routine()

        atexit.register(exit_routine)
        signal.signal(signal.SIGTERM, term_handler)

        tracer = viztracer.VizTracer(**self._viztracer_kwargs)
        tracer.start()
        tracer.pid_suffix = True
        tracer.output_file = os.path.join(self._multiprocess_output_dir,
                                          "result.json")
        self._run()
        atexit._run_exitfuncs()
Exemple #18
0
    def coprocess(self, directory=None):
        """Start a coprocess server.

        Return a CoProcess object that is the manager for the coprocess.
        Use the `start` method on that to actually run coprocess method.
        """
        pid, conn = _fork_coprocess(directory)
        if pid == 0:  # child
            sys.excepthook = sys.__excepthook__
            proc = None
            signal.signal(signal.SIGCHLD, signal.SIG_DFL)
            self._procs = {}
            self._zombies = {}
            self.splitter = None
            atexit._run_exitfuncs()
            atexit._clear()
            sys.stdout.flush()
            sys.stderr.flush()
            _close_stdin()
            _redirect(1, "/tmp/devtest-coprocess-{}.stdout".format(os.getpid()))
            _redirect(2, "/tmp/devtest-coprocess-{}.stderr".format(os.getpid()))
            try:
                get_kernel().run(_coprocess_server_coro, conn)
            except KeyboardInterrupt:
                pass
            except:  # noqa
                traceback.print_exc(file=sys.stderr)
            os._exit(0)
        else:
            proc = CoProcess(pid, conn)
            proc.progname = "CoProcess"
            self._procs[proc.pid] = proc
        logging.notice("ProcessManager: coprocess server with PID: {}".format(pid))
        return proc
def exit():
    """
    Causes python to exit without garbage-collecting any objects, and thus avoids
    calling object destructor methods. This is a sledgehammer workaround for 
    a variety of bugs in PyQt and Pyside that cause crashes on exit.
    
    This function does the following in an attempt to 'safely' terminate
    the process:
    
    * Invoke atexit callbacks
    * Close all open file handles
    * os._exit()
    
    Note: there is some potential for causing damage with this function if you
    are using objects that _require_ their destructors to be called (for example,
    to properly terminate log files, disconnect from devices, etc). Situations
    like this are probably quite rare, but use at your own risk.
    """
    
    ## first disable our own cleanup function; won't be needing it.
    setConfigOptions(exitCleanup=False)
    
    ## invoke atexit callbacks
    atexit._run_exitfuncs()
    
    ## close file handles
    if sys.platform == 'darwin':
        for fd in range(3, 4096):
            if fd not in [7]:  # trying to close 7 produces an illegal instruction on the Mac.
                os.close(fd)
    else:
        os.closerange(3, 4096) ## just guessing on the maximum descriptor count..

    os._exit(0)
    def test_order(self):
        # be sure handlers are executed in reverse order
        atexit.register(h1)
        atexit.register(h2)
        atexit.register(h3)
        atexit._run_exitfuncs()

        self.assertEqual(self.stream.getvalue(), "h3\nh2\nh1\n")
 def run():
     try:
         atexit._clear()
         fn()
     except Exception:
         raise
     finally:
         atexit._run_exitfuncs()
Exemple #22
0
    def assert_raises_unraisable(self, exc_type, func, *args):
        with support.catch_unraisable_exception() as cm:
            atexit.register(func, *args)
            atexit._run_exitfuncs()

            self.assertEqual(cm.unraisable.object, func)
            self.assertEqual(cm.unraisable.exc_type, exc_type)
            self.assertEqual(type(cm.unraisable.exc_value), exc_type)
 def test_bound_methods(self):
     l = []
     atexit.register(l.append, 5)
     atexit._run_exitfuncs()
     self.assertEqual(l, [5])
     atexit.unregister(l.append)
     atexit._run_exitfuncs()
     self.assertEqual(l, [5])
Exemple #24
0
    def test_order(self):
        # be sure handlers are executed in reverse order
        atexit.register(h1)
        atexit.register(h2)
        atexit.register(h3)
        atexit._run_exitfuncs()

        self.assertEqual(self.stream.getvalue(), "h3\nh2\nh1\n")
Exemple #25
0
def test_no_hold_on_default_false():
    browser.open('http://todomvc.com/examples/emberjs/')
    driver = browser.driver
    browser.element('#new-todo').type('a').press_enter()

    atexit._run_exitfuncs()

    assert not Help(driver).has_browser_still_alive()
    def test_args(self):
        # be sure args are handled properly
        atexit.register(h1)
        atexit.register(h4)
        atexit.register(h4, 4, kw="abc")
        atexit._run_exitfuncs()

        self.assertEqual(self.stream.getvalue(), "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n")
Exemple #27
0
def worker(inqueue,
           outqueue,
           stop_pipe,
           initializer=None,
           initargs=(),
           maxtasks=None,
           wrap_exception=False):
    def run_exitfuncs(num, frame):
        atexit._run_exitfuncs()

    signal.signal(signal.SIGTERM, run_exitfuncs)

    if (maxtasks
            is not None) and not (isinstance(maxtasks, int) and maxtasks >= 1):
        raise AssertionError("Maxtasks {!r} is not valid".format(maxtasks))
    put = outqueue.put
    get = inqueue.get
    if hasattr(inqueue, '_writer'):
        inqueue._writer.close()
        outqueue._reader.close()

    if initializer is not None:
        initializer(*initargs)

    completed = 0
    while maxtasks is None or (maxtasks and completed < maxtasks):
        if stop_pipe.poll():
            break

        try:
            task = get()
        except (EOFError, OSError):
            util.debug('worker got EOFError or OSError -- exiting')
            break

        if task is None:
            util.debug('worker got sentinel -- exiting')
            break

        job, i, func, args, kwds = task
        try:
            result = (True, func(*args, **kwds))
        except Exception as e:
            if wrap_exception and func is not _helper_reraises_exception:
                e = ExceptionWithTraceback(e, e.__traceback__)
            result = (False, e)
        try:
            put((job, i, result))
        except Exception as e:
            wrapped = MaybeEncodingError(e, result[1])
            util.debug("Possible encoding error while sending result: %s" %
                       (wrapped))
            put((job, i, (False, wrapped)))

        task = job = result = func = args = kwds = None
        completed += 1
    util.debug('worker exiting after %d tasks' % completed)
    atexit._run_exitfuncs()
Exemple #28
0
def handle_signal_(sig, sigframe):
    print
    sys.stdout.flush()
    print >>sys.stderr, "Interrupted by signal %d" % sig
    sys.stderr.flush()
    # run registered exit funcs
    atexit._run_exitfuncs()  # pragma: uncovered
    # do not wait for threads termination
    os._exit(128 + sig)  # pragma: uncovered
Exemple #29
0
def test_hold_on_explicit_true():
    browser.config.hold_browser_open = True
    browser.open('http://todomvc.com/examples/emberjs/')
    browser.element('#new-todo').type('a').press_enter()

    atexit._run_exitfuncs()
    browser.element('#new-todo').type('b').press_enter()

    browser.all('#todo-list>li').should(have.texts('a', 'b'))
Exemple #30
0
def handle_signal_(sig, sigframe):
    print
    sys.stdout.flush()
    print >> sys.stderr, "Interrupted by signal %d" % sig
    sys.stderr.flush()
    # run registered exit funcs
    atexit._run_exitfuncs()  # pragma: uncovered
    # do not wait for threads termination
    os._exit(128 + sig)  # pragma: uncovered
Exemple #31
0
    def test_args(self):
        # be sure args are handled properly
        atexit.register(h1)
        atexit.register(h4)
        atexit.register(h4, 4, kw="abc")
        atexit._run_exitfuncs()

        self.assertEqual(self.stream.getvalue(),
                            "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n")
    def test_bound_methods(self):
        l = []
        atexit.register(l.append, 5)
        atexit._run_exitfuncs()
        self.assertEqual(l, [5])

        atexit.unregister(l.append)
        atexit._run_exitfuncs()
        self.assertEqual(l, [5])
Exemple #33
0
    def test_clear(self):
        a = [0]
        def inc():
            a[0] += 1

        atexit.register(inc)
        atexit._clear()
        atexit._run_exitfuncs()

        self.assertEqual(a[0], 0)
    def test_clear(self):
        a = [0]
        def inc():
            a[0] += 1

        atexit.register(inc)
        atexit._clear()
        atexit._run_exitfuncs()

        self.assertEqual(a[0], 0)
    def test_stress(self):
        a = [0]
        def inc():
            a[0] += 1

        for i in range(128):
            atexit.register(inc)
        atexit._run_exitfuncs()

        self.assertEqual(a[0], 128)
    def test_broken_trial(self):
        """Test that broken trials are detected"""
        with create_experiment() as (cfg, experiment, client):
            trial = client.suggest()
            assert trial.status == 'reserved'

            atexit._run_exitfuncs()

            assert client._pacemakers == {}
            assert client.get_trial(trial).status == 'broken'
Exemple #37
0
 def run():
     """This wrapper will handle the AutoDist destructor and garbage collections."""
     try:
         atexit._clear()  # TensorFlow also uses atexit, but running its exitfuncs cause some issues
         train_and_save()
         fine_tune()
     except Exception:
         raise
     finally:
         atexit._run_exitfuncs()
Exemple #38
0
    def test_stress(self):
        a = [0]
        def inc():
            a[0] += 1

        for i in range(128):
            atexit.register(inc)
        atexit._run_exitfuncs()

        self.assertEqual(a[0], 128)
Exemple #39
0
def restart():
    if hasattr(atexit, "_run_exitfuncs"):
        # We're about to leave in a way that's not expected by
        # Python.
        # This means that some things, including atexit callbacks,
        # won't be run.
        # We want them to run because ircbot.py relies on them, so
        # this is our kind-of CPython hack.
        atexit._run_exitfuncs()

    os.execvp(sys.executable, [sys.executable] + sys.argv)
Exemple #40
0
    def exec_():
        """ This is a workaround for those systems that 
        crash on Qt exit. It is ensured that all registered
        exit functions are executed before Qt the application exits. """
        # pylint: disable=W0212

        QtGui.QApplication.exec_()
        try:
            atexit._run_exitfuncs()
        except:  # pylint: disable=W0702
            pass  # _run_exitfuncs already prints errors to stderr
Exemple #41
0
 def exec_():
     """ This is a workaround for those systems that 
     crash on Qt exit. It is ensured that all registered
     exit functions are executed before Qt the application exits. """
     # pylint: disable=W0212
     
     QtGui.QApplication.exec_()
     try: 
         atexit._run_exitfuncs()
     except: # pylint: disable=W0702
         pass # _run_exitfuncs already prints errors to stderr
 def test_sys_override(self):
     # be sure a preset sys.exitfunc is handled properly
     exfunc = sys.exitfunc
     sys.exitfunc = self.h1
     reload(atexit)
     try:
         atexit.register(self.h2)
         atexit._run_exitfuncs()
     finally:
         sys.exitfunc = exfunc
     self.assertEqual(self.subst_io.getvalue(), "h2\nh1\n")
Exemple #43
0
 def shutdown(self, force_quit_timeout=0):
     """
     Shutdown the queue (after finishing any pending requests).
     """
     self.logger.info('Shutting down threadpool')
     # Add a shutdown request for every worker
     for i in range(len(self.workers)):
         self.queue.put(PasteThreadPool.SHUTDOWN)
     # Wait for each thread to terminate
     hung_workers = []
     for worker in self.workers:
         worker.join(0.5)
         if worker.isAlive():
             hung_workers.append(worker)
     zombies = []
     for thread_id in self.dying_threads:
         if self.thread_exists(thread_id):
             zombies.append(thread_id)
     if hung_workers or zombies:
         self.logger.info("%s workers didn't stop properly, and %s zombies",
                          len(hung_workers), len(zombies))
         if hung_workers:
             for worker in hung_workers:
                 self.kill_worker(worker.thread_id)
             self.logger.info('Workers killed forcefully')
         if force_quit_timeout:
             hung = []
             timed_out = False
             need_force_quit = bool(zombies)
             for workers in self.workers:
                 if not timed_out and worker.isAlive():
                     timed_out = True
                     worker.join(force_quit_timeout)
                 if worker.isAlive():
                     print "Worker %s won't die" % worker
                     need_force_quit = True
             if need_force_quit:
                 import atexit
                 # Remove the threading atexit callback
                 for callback in list(atexit._exithandlers):
                     func = getattr(callback[0], 'im_func', None)
                     if not func:
                         continue
                     globs = getattr(func, 'func_globals', {})
                     mod = globs.get('__name__')
                     if mod == 'threading':
                         atexit._exithandlers.remove(callback)
                 atexit._run_exitfuncs()
                 print 'Forcefully exiting process'
                 os._exit(3)
             else:
                 self.logger.info('All workers eventually killed')
     else:
         self.logger.info('All workers stopped')
Exemple #44
0
 def test_sys_override(self):
     # be sure a preset sys.exitfunc is handled properly
     exfunc = sys.exitfunc
     sys.exitfunc = self.h1
     reload(atexit)
     try:
         atexit.register(self.h2)
         atexit._run_exitfuncs()
     finally:
         sys.exitfunc = exfunc
     self.assertEqual(self.subst_io.getvalue(), "h2\nh1\n")
def Terminate(reason = ''):
    import logmodule as log
    log.general.Log('bluepy.Terminate - Reason: %s' % reason, log.LGNOTICE)
    try:
        if 'sm' in __builtins__:
            sm.ChainEvent('ProcessShutdown')
    except:
        log.LogException()

    atexit._run_exitfuncs()
    blue.os.Terminate(0)
Exemple #46
0
def exec_(argv, env=None):  # never returns
    """Wrapper to os.execv which runs any atexit handlers (for coverage's sake).
    Like os.execv, this function never returns.
    """
    if env is None:
        env = os.environ

    # in python3, sys.exitfunc has gone away, and atexit._run_exitfuncs seems to be the only pubic-ish interface
    #   https://hg.python.org/cpython/file/3.4/Modules/atexitmodule.c#l289
    import atexit
    atexit._run_exitfuncs()  # pylint:disable=protected-access
    os.execvpe(argv[0], argv, env)
Exemple #47
0
    def terminate(self, signal_number, stack_frame):
        """ Signal handler for end-process signals.
            :Return: ``None``

            Signal handler for the ``signal.SIGTERM`` signal. Performs the
            following step:

            * Raise a ``SystemExit`` exception explaining the signal.
        """

        # Force atexit functions to run, as they don't seem to be when SystemExit is raised.
        atexit._run_exitfuncs()
        raise SystemExit('Terminating on signal {:d}'.format(signal_number))
Exemple #48
0
def exec_(argv):  # never returns
    """Wrapper to os.execv which shows the command and runs any atexit handlers (for coverage's sake).
    Like os.execv, this function never returns.
    """
    # info('EXEC' + colorize(argv))  # TODO: debug logging by environment variable

    # in python3, sys.exitfunc has gone away, and atexit._run_exitfuncs seems to be the only pubic-ish interface
    #   https://hg.python.org/cpython/file/3.4/Modules/atexitmodule.c#l289
    import atexit
    atexit._run_exitfuncs()

    from os import execv
    execv(argv[0], argv)
Exemple #49
0
def exec_(argv):
    """Wrapper to os.execv which shows the command and runs any atexit handlers (for coverage's sake).
    Like os.execv, this function never returns.
    """
    info(colorize(argv))

    # in python3, sys.exitfunc has gone away, and atexit._run_exitfuncs seems to be the only pubic-ish interface
    #   https://hg.python.org/cpython/file/3.4/Modules/atexitmodule.c#l289
    import atexit
    atexit._run_exitfuncs()  # pylint:disable=protected-access

    from os import execv
    execv(argv[0], argv)  # never returns
Exemple #50
0
def exit(exitcode=0):
    """
    Causes python to exit without garbage-collecting any objects, and thus
    avoids calling object destructor methods. This is a sledgehammer
    workaround for a variety of bugs in PyQt and Pyside that cause crashes
    on exit.

    This function does the following in an attempt to 'safely' terminate
    the process:

    * Invoke atexit callbacks
    * Close all open file handles
    * os._exit()

    Note: there is some potential for causing damage with this function if you
    are using objects that _require_ their destructors to be called (for
    example, to properly terminate log files, disconnect from devices, etc).
    Situations like this are probably quite rare, but use at your own risk.

    @param int exitcode: system exit code
    """

    if has_pyqtgraph:
        # first disable our pyqtgraph's cleanup function; won't be needing it.
        pyqtgraph.setConfigOptions(exitCleanup=False)

    # invoke atexit callbacks
    atexit._run_exitfuncs()

    # close file handles
    fd_min = 3
    fd_max = 4096
    fd_except = set()

    fd_set = set(range(fd_min, fd_max))

    # in this subprocess we redefine the stdout, therefore on Unix systems we
    # need to handle the opened file descriptors, see PEP 446:
    #       https://www.python.org/dev/peps/pep-0446/
    if sys.platform in ['linux', 'darwin']:

        if sys.platform == 'darwin':
            # trying to close 7 produces an illegal instruction on the Mac.
            fd_except.add(7)

        # remove specified file descriptor
        fd_set = fd_set - fd_except

        close_fd(fd_set)

    os._exit(exitcode)
    def test_unregister(self):
        a = [0]
        def inc():
            a[0] += 1
        def dec():
            a[0] -= 1

        for i in range(4):
            atexit.register(inc)
        atexit.register(dec)
        atexit.unregister(inc)
        atexit._run_exitfuncs()

        self.assertEqual(a[0], -1)
 def user_return(self,frame,retval):
     """
     Reimplemented to report program termination to the debug server.
     
     @param frame the frame object
     @param retval the return value of the program
     """
     # The program has finished if we have just left the first frame.
     if frame == self._dbgClient.mainFrame and \
         self._mainThread:
         atexit._run_exitfuncs()
         self._dbgClient.progTerminated(retval)
     elif frame is not self.stepFrame:
         self.stepFrame = None
         self.user_line(frame)
Exemple #53
0
 def test_order(self):
     # be sure handlers are executed in reverse order
     s = StringIO.StringIO()
     sys.stdout = sys.stderr = s
     save_handlers = atexit._exithandlers
     atexit._exithandlers = []
     try:
         atexit.register(self.h1)
         atexit.register(self.h2)
         atexit.register(self.h3)
         atexit._run_exitfuncs()
     finally:
         sys.stdout = sys.__stdout__
         sys.stderr = sys.__stderr__
         atexit._exithandlers = save_handlers
     self.assertEqual(s.getvalue(), "h3\nh2\nh1\n")
Exemple #54
0
 def test_args(self):
     # be sure args are handled properly
     s = StringIO.StringIO()
     sys.stdout = sys.stderr = s
     save_handlers = atexit._exithandlers
     atexit._exithandlers = []
     try:
         atexit.register(self.h1)
         atexit.register(self.h4)
         atexit.register(self.h4, 4, kw="abc")
         atexit._run_exitfuncs()
     finally:
         sys.stdout = sys.__stdout__
         sys.stderr = sys.__stderr__
         atexit._exithandlers = save_handlers
     self.assertEqual(s.getvalue(), "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n")
Exemple #55
0
 def test_sys_override(self):
     # be sure a preset sys.exitfunc is handled properly
     save_handlers = atexit._exithandlers
     atexit._exithandlers = []
     exfunc = sys.exitfunc
     sys.exitfunc = self.h1
     reload(atexit)
     s = StringIO.StringIO()
     sys.stdout = sys.stderr = s
     try:
         atexit.register(self.h2)
         atexit._run_exitfuncs()
     finally:
         sys.stdout = sys.__stdout__
         sys.stderr = sys.__stderr__
         atexit._exithandlers = save_handlers
         sys.exitfunc = exfunc
     self.assertEqual(s.getvalue(), "h2\nh1\n")
Exemple #56
0
 def run(self, args):
     sys_argv = self.debugger.restart_argv()
     if sys_argv and len(sys_argv) > 0:
         confirmed = self.confirm('Restart (execv)', False)
         if confirmed:
             self.msg(Mmisc.wrapped_lines("Re exec'ing:", repr(sys_argv),
                                          self.settings['width']))
             # Run atexit finalize routines. This seems to be Kosher:
             # http://mail.python.org/pipermail/python-dev/2009-February/085791.html # NOQA
             try:
                 atexit._run_exitfuncs()
             except:
                 pass
             os.execvp(sys_argv[0], sys_argv)
             pass
         pass
     else:
         self.errmsg("No executable file and command options recorded.")
         pass
     return
Exemple #57
0
def cleanup(*args):
    # in case of exception, current function should be removed
    # of exit functions list
    try:
        if atexit._exithandlers[0][0] == cleanup:
            atexit._exithandlers.pop(0)
    except: pass
    # run other exit functions before calling os._exit
    atexit._run_exitfuncs()
    # compute exit msg and code
    msg=''
    if not args:
        code = 0
    elif len(args) == 1: # sys.exit, exit
        code = int(args[0])
    elif len(args) == 2: # signal catched
        code = int(args[0])
    elif len(args) == 3: # exception
        code = 1
    else:                # unknown
        msg = 'unknown'
        code = 1
    # Clean tmp dir unless specified
    if not keeptest and (not keepfail or code == 0):
        os.chdir(tmpdir)
        shutil.rmtree(tstdir)
    # Call exit fuinctions
    if code == 0:
        success()
    elif len(args) == 2: # interrupt
        interrupted(code=code)
    elif len(args) == 3: # exception
        excname = traceback.format_exception_only(
            args[0], args[1])[-1].strip()
        traceback.print_exception(*args)
        failure(excname, code)
    else:
        failure(msg=msg, code=code)

    assert 0
Exemple #58
0
 def applicationWillTerminate_(self, note):
     import atexit
     atexit._run_exitfuncs()
Exemple #59
0
 def test_order(self):
     atexit.register(self.h1)
     atexit.register(self.h2)
     atexit.register(self.h3)
     atexit._run_exitfuncs()
     self.assertEqual(self.subst_io.getvalue(), "h3\nh2\nh1\n")
Exemple #60
0
            # Update
            try:
                update.update()
            except Exception, err:
                print "Update error: %s" % err

            # Close log files
            logger = sys.modules["main"].logging.getLogger()

            for handler in logger.handlers[:]:
                handler.flush()
                handler.close()
                logger.removeHandler(handler)

            atexit._run_exitfuncs()

    except Exception, err:  # Prevent closing
        import traceback
        try:
            import logging
            logging.exception("Unhandled exception: %s" % err)
        except Exception, log_err:
            print "Failed to log error:", log_err
            traceback.print_exc()
        from Config import config
        traceback.print_exc(file=open(config.log_dir + "/error.log", "a"))

    if main and main.update_after_shutdown:  # Updater
        # Restart
        gc.collect()  # Garbage collect