Python atexit.register() Examples

The following are 30 code examples for showing how to use atexit.register(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module atexit , or try the search function .

Example 1
Project: aegea   Author: kislyuk   File: weakref.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, obj, func, *args, **kwargs):
        if not self._registered_with_atexit:
            # We may register the exit function more than once because
            # of a thread race, but that is harmless
            import atexit
            atexit.register(self._exitfunc)
            finalize._registered_with_atexit = True
        info = self._Info()
        info.weakref = ref(obj, self)
        info.func = func
        info.args = args
        info.kwargs = kwargs or None
        info.atexit = True
        info.index = next(self._index_iter)
        self._registry[self] = info
        finalize._dirty = True 
Example 2
Project: cherrypy   Author: cherrypy   File: wspbus.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def start(self):
        """Start all services."""
        atexit.register(self._clean_exit)

        self.state = states.STARTING
        self.log('Bus STARTING')
        try:
            self.publish('start')
            self.state = states.STARTED
            self.log('Bus STARTED')
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            self.log('Shutting down due to error in start listener:',
                     level=40, traceback=True)
            e_info = sys.exc_info()[1]
            try:
                self.exit()
            except Exception:
                # Any stop/exit errors will be logged inside publish().
                pass
            # Re-raise the original error
            raise e_info 
Example 3
Project: soccer-matlab   Author: utra-robosoccer   File: wrappers.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, constructor):
    """Step environment in a separate process for lock free paralellism.

    The environment will be created in the external process by calling the
    specified callable. This can be an environment class, or a function
    creating the environment and potentially wrapping it. The returned
    environment should not access global variables.

    Args:
      constructor: Callable that creates and returns an OpenAI gym environment.

    Attributes:
      observation_space: The cached observation space of the environment.
      action_space: The cached action space of the environment.
    """
    self._conn, conn = multiprocessing.Pipe()
    self._process = multiprocessing.Process(
        target=self._worker, args=(constructor, conn))
    atexit.register(self.close)
    self._process.start()
    self._observ_space = None
    self._action_space = None 
Example 4
Project: soccer-matlab   Author: utra-robosoccer   File: wrappers.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, constructor):
    """Step environment in a separate process for lock free paralellism.

    The environment will be created in the external process by calling the
    specified callable. This can be an environment class, or a function
    creating the environment and potentially wrapping it. The returned
    environment should not access global variables.

    Args:
      constructor: Callable that creates and returns an OpenAI gym environment.

    Attributes:
      observation_space: The cached observation space of the environment.
      action_space: The cached action space of the environment.
    """
    self._conn, conn = multiprocessing.Pipe()
    self._process = multiprocessing.Process(
        target=self._worker, args=(constructor, conn))
    atexit.register(self.close)
    self._process.start()
    self._observ_space = None
    self._action_space = None 
Example 5
Project: jawfish   Author: war-and-code   File: regrtest.py    License: MIT License 6 votes vote down vote up
def replace_stdout():
    """Set stdout encoder error handler to backslashreplace (as stderr error
    handler) to avoid UnicodeEncodeError when printing a traceback"""
    import atexit

    stdout = sys.stdout
    sys.stdout = open(stdout.fileno(), 'w',
        encoding=stdout.encoding,
        errors="backslashreplace",
        closefd=False,
        newline='\n')

    def restore_stdout():
        sys.stdout.close()
        sys.stdout = stdout
    atexit.register(restore_stdout) 
Example 6
Project: dataflow   Author: tensorpack   File: concurrency.py    License: Apache License 2.0 6 votes vote down vote up
def ensure_proc_terminate(proc):
    """
    Make sure processes terminate when main process exit.

    Args:
        proc (multiprocessing.Process or list)
    """
    if isinstance(proc, list):
        for p in proc:
            ensure_proc_terminate(p)
        return

    def stop_proc_by_weak_ref(ref):
        proc = ref()
        if proc is None:
            return
        if not proc.is_alive():
            return
        proc.terminate()
        proc.join()

    assert isinstance(proc, mp.Process)
    atexit.register(stop_proc_by_weak_ref, weakref.ref(proc)) 
Example 7
Project: verge3d-blender-addon   Author: Soft8Soft   File: manager.py    License: GNU General Public License v3.0 6 votes vote down vote up
def runServerProc(cls):
        sys.path.append(join(cls.root, 'manager'))

        if cls.isThreaded:
            import server
            srv = server.AppManagerServer()
            srv.start(cls.modPackage)
        else:
            system = platform.system()

            if system == 'Windows':
                pythonPath = join(cls.root, 'python', 'windows', 'pythonw.exe')
            elif system == 'Darwin':
                pythonPath = 'python3'
            else:
                pythonPath = 'python3'

            args = [pythonPath, join(cls.root, 'manager', 'server.py'), cls.modPackage]
            cls.subProcs.append(subprocess.Popen(args))
            atexit.register(cls.killSubProcs) 
Example 8
Project: verge3d-blender-addon   Author: Soft8Soft   File: profilehooks.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, fn, skip=0, filename=None, immediate=False, dirs=False,
                 sort=None, entries=40, stdout=True):
        """Creates a profiler for a function.

        Every profiler has its own log file (the name of which is derived
        from the function name).

        FuncProfile registers an atexit handler that prints profiling
        information to sys.stderr when the program terminates.
        """
        self.fn = fn
        self.skip = skip
        self.filename = filename
        self._immediate = immediate
        self.stdout = stdout
        self.dirs = dirs
        self.sort = sort or ('cumulative', 'time', 'calls')
        if isinstance(self.sort, str):
            self.sort = (self.sort, )
        self.entries = entries
        self.reset_stats()
        if not self.immediate:
            atexit.register(self.atexit) 
Example 9
Project: verge3d-blender-addon   Author: Soft8Soft   File: profilehooks.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, fn):
            """Creates a profiler for a function.

            Every profiler has its own log file (the name of which is derived
            from the function name).

            HotShotFuncCoverage registers an atexit handler that prints
            profiling information to sys.stderr when the program terminates.

            The log file is not removed and remains there to clutter the
            current working directory.
            """
            self.fn = fn
            self.logfilename = "%s.%d.cprof" % (fn.__name__, os.getpid())
            self.profiler = _hotshot.coverage(self.logfilename)
            self.ncalls = 0
            atexit.register(self.atexit) 
Example 10
Project: verge3d-blender-addon   Author: Soft8Soft   File: profilehooks.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, fn):
        """Creates a profiler for a function.

        Every profiler has its own log file (the name of which is derived
        from the function name).

        TraceFuncCoverage registers an atexit handler that prints
        profiling information to sys.stderr when the program terminates.

        The log file is not removed and remains there to clutter the
        current working directory.
        """
        self.fn = fn
        self.logfilename = "%s.%d.cprof" % (fn.__name__, os.getpid())
        self.ncalls = 0
        atexit.register(self.atexit) 
Example 11
Project: hadrian   Author: modelop   File: defs.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self):
        """Create the main mode.

        If titus.inspector.defs.CONFIG_DIRECTORY_EXISTS is ``True``, get the readline history file from the user's titus.inspector.defs.CONFIG_DIRECTORY.
        """

        if CONFIG_DIRECTORY_EXISTS:
            self.historyPath = os.path.join(os.path.expanduser(CONFIG_DIRECTORY), self.historyFileName)
            if not os.path.exists(self.historyPath):
                open(self.historyPath, "w").close()

            self.active = True
            self.tabCompleter = TabCompleter(self)
            readline.read_history_file(self.historyPath)
            readline.set_completer(self.tabCompleter.complete)

            def writehistory():
                if self.active:
                    readline.write_history_file(self.historyPath)
            atexit.register(writehistory) 
Example 12
Project: misp42splunk   Author: remg427   File: test_fixers.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_comments(self):
        b = """
            import sys # Foo
            sys.exitfunc = f # Blah
            """
        a = """
            import sys
            import atexit # Foo
            atexit.register(f) # Blah
            """
        self.check(b, a)

        b = """
            import apples, sys, crumbs, larry # Pleasant comments
            sys.exitfunc = func
            """
        a = """
            import apples, sys, crumbs, larry, atexit # Pleasant comments
            atexit.register(func)
            """
        self.check(b, a) 
Example 13
Project: qutebrowser   Author: qutebrowser   File: quitter.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _shutdown_2(self, status: int, is_restart: bool) -> None:
        """Second stage of shutdown."""
        log.destroy.debug("Stage 2 of shutting down...")

        # Tell everything to shut itself down
        self.shutting_down.emit()

        # Delete temp basedir
        if ((self._args.temp_basedir or self._args.temp_basedir_restarted) and
                not is_restart):
            atexit.register(shutil.rmtree, self._args.basedir,
                            ignore_errors=True)

        # Now we can hopefully quit without segfaults
        log.destroy.debug("Deferring QApplication::exit...")
        # We use a singleshot timer to exit here to minimize the likelihood of
        # segfaults.
        QTimer.singleShot(0, functools.partial(self._shutdown_3, status)) 
Example 14
Project: brownie   Author: eth-brownie   File: rpc.py    License: MIT License 6 votes vote down vote up
def reset(self) -> str:
        """
        Revert the EVM to the initial state when loaded.

        This action clears the undo buffer.
        """
        self._snapshot_id = None
        self._undo_buffer.clear()
        self._redo_buffer.clear()
        self._reset_id = self._current_id = self._revert(self._reset_id)
        return f"Block height reset to {web3.eth.blockNumber}"


# objects that will update whenever the RPC is reset or reverted must register
# by calling to this function. The must also include _revert and _reset methods
# to recieve notifications from this object 
Example 15
Project: moler   Author: nokia   File: runner.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, executor=None):
        """Create instance of ThreadPoolExecutorRunner class"""
        self._tick = 0.005  # Tick for sleep or partial timeout
        self._in_shutdown = False
        self._i_own_executor = False
        self._was_timeout_called = False
        self.executor = executor
        self.logger = logging.getLogger('moler.runner.thread-pool')
        self.logger.debug("created")
        atexit.register(self.shutdown)
        if executor is None:
            max_workers = 1000  # max 1000 threads in pool
            try:  # concurrent.futures  v.3.2.0 introduced prefix we like :-)
                self.executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix='ThrdPoolRunner')
            except TypeError as exc:
                if ('unexpected' in str(exc)) and ('thread_name_prefix' in str(exc)):
                    self.executor = ThreadPoolExecutor(max_workers=max_workers)
                else:
                    raise
            self.logger.debug("created own executor {!r}".format(self.executor))
            self._i_own_executor = True
        else:
            self.logger.debug("reusing provided executor {!r}".format(self.executor)) 
Example 16
Project: backend.ai-manager   Author: lablup   File: __main__.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def main(ctx, config_path, debug):
    cfg = load_config(config_path)
    setproctitle(f"backend.ai: manager.cli {cfg['etcd']['namespace']}")
    if 'file' in cfg['logging']['drivers']:
        cfg['logging']['drivers'].remove('file')
    # log_endpoint = f'tcp://127.0.0.1:{find_free_port()}'
    log_sockpath = Path(f'/tmp/backend.ai/ipc/manager-cli-{os.getpid()}.sock')
    log_sockpath.parent.mkdir(parents=True, exist_ok=True)
    log_endpoint = f'ipc://{log_sockpath}'
    logger = Logger(cfg['logging'], is_master=True, log_endpoint=log_endpoint)
    ctx.obj = CLIContext(
        logger=logger,
        config=cfg,
    )

    def _clean_logger():
        try:
            os.unlink(log_sockpath)
        except FileNotFoundError:
            pass

    atexit.register(_clean_logger) 
Example 17
Project: recruit   Author: Frank-qlu   File: serving.py    License: Apache License 2.0 6 votes vote down vote up
def generate_adhoc_ssl_context():
    """Generates an adhoc SSL context for the development server."""
    crypto = _get_openssl_crypto_module()
    import tempfile
    import atexit

    cert, pkey = generate_adhoc_ssl_pair()
    cert_handle, cert_file = tempfile.mkstemp()
    pkey_handle, pkey_file = tempfile.mkstemp()
    atexit.register(os.remove, pkey_file)
    atexit.register(os.remove, cert_file)

    os.write(cert_handle, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    os.write(pkey_handle, crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    os.close(cert_handle)
    os.close(pkey_handle)
    ctx = load_ssl_context(cert_file, pkey_file)
    return ctx 
Example 18
Project: holodeck   Author: BYU-PCCL   File: environments.py    License: MIT License 6 votes vote down vote up
def __windows_start_process__(self, binary_path, task_key, verbose):
        import win32event
        out_stream = sys.stdout if verbose else open(os.devnull, 'w')
        loading_semaphore = win32event.CreateSemaphore(None, 0, 1,
                                                       'Global\\HOLODECK_LOADING_SEM' + self._uuid)
        self._world_process = \
            subprocess.Popen([binary_path, task_key, '-HolodeckOn', '-LOG=HolodeckLog.txt',
                              '-ForceRes', '-ResX=' + str(self._window_size[1]), '-ResY=' +
                              str(self._window_size[0]), '-TicksPerSec=' + str(self._ticks_per_sec),
                              '--HolodeckUUID=' + self._uuid],
                             stdout=out_stream, stderr=out_stream)

        atexit.register(self.__on_exit__)
        response = win32event.WaitForSingleObject(loading_semaphore, 100000)  # 100 second timeout
        if response == win32event.WAIT_TIMEOUT:
            raise HolodeckException("Timed out waiting for binary to load") 
Example 19
Project: Caffe-Python-Data-Layer   Author: liuxianming   File: TripletDataLayer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setup(self, bottom, top):
        # setup functions from super class
        super(TripletDataLayer, self).setup(bottom, top)
        print("Using Triplet Python Data Layer")
        # prefetch or not: default = False
        self._sampling_type = self._layer_params.get('type', 'RANDOM')
        self._prefetch = self._layer_params.get('prefetch', False)
        """Construct kwargs:
        possible fields:
        k - number of candidates when hard negative sampling
        m - similarity graph filename for hard negative sampling
        n - number of iterations before hard negative sampling
        """
        kwargs = {}
        for key, value in self._layer_params.iteritems():
            if key.lower() in ['k', 'm', 'n']:
                kwargs[key.lower()] = value
        if self._prefetch:
            # using prefetch to generate mini-batches
            self._conn, conn = Pipe()
            self._prefetch_process = TripletPrefetcher(
                conn,
                self._label, self._data,
                self._mean, self._resize, self._batch_size,
                self._sampling_type, **kwargs
            )
            print("Start Prefetching Process...")
            self._prefetch_process.start()

            def cleanup():
                print("Terminating Prefetching Processs...")
                self._prefetch_process.terminate()
                self._prefetch_process.join()
                self._conn.close()
            atexit.register(cleanup)
        else:
            self._sampler = TripletSampler(
                self._sampling_type, self._label, **kwargs)
        self.reshape(bottom, top) 
Example 20
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: util.py    License: MIT License 5 votes vote down vote up
def __init__(self, protected_path, timeout=0.0, delay=0.05):
        """Create new :class:`LockFile` object."""
        self.lockfile = protected_path + '.lock'
        self._lockfile = None
        self.timeout = timeout
        self.delay = delay
        self._lock = Event()
        atexit.register(self.release) 
Example 21
Project: cherrypy   Author: cherrypy   File: test_wsgi_unix_socket.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect(self):
        """
        Override the connect method and assign a unix socket as a transport.
        """
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.connect(self.path)
        self.sock = sock
        atexit.register(lambda: os.remove(self.path)) 
Example 22
Project: zmirror   Author: aploium   File: initialise.py    License: MIT License 5 votes vote down vote up
def init(autoreset=False, convert=None, strip=None, wrap=True):

    if not wrap and any([autoreset, convert, strip]):
        raise ValueError('wrap=False conflicts with any other arg=True')

    global wrapped_stdout, wrapped_stderr
    global orig_stdout, orig_stderr

    orig_stdout = sys.stdout
    orig_stderr = sys.stderr

    if sys.stdout is None:
        wrapped_stdout = None
    else:
        sys.stdout = wrapped_stdout = \
            wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
    if sys.stderr is None:
        wrapped_stderr = None
    else:
        sys.stderr = wrapped_stderr = \
            wrap_stream(orig_stderr, convert, strip, autoreset, wrap)

    global atexit_done
    if not atexit_done:
        atexit.register(reset_all)
        atexit_done = True 
Example 23
Project: multibootusb   Author: mbusb   File: initialise.py    License: GNU General Public License v2.0 5 votes vote down vote up
def init(autoreset=False, convert=None, strip=None, wrap=True):

    if not wrap and any([autoreset, convert, strip]):
        raise ValueError('wrap=False conflicts with any other arg=True')

    global wrapped_stdout, wrapped_stderr
    global orig_stdout, orig_stderr

    orig_stdout = sys.stdout
    orig_stderr = sys.stderr

    if sys.stdout is None:
        wrapped_stdout = None
    else:
        sys.stdout = wrapped_stdout = \
            wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
    if sys.stderr is None:
        wrapped_stderr = None
    else:
        sys.stderr = wrapped_stderr = \
            wrap_stream(orig_stderr, convert, strip, autoreset, wrap)

    global atexit_done
    if not atexit_done:
        atexit.register(reset_all)
        atexit_done = True 
Example 24
Project: friendly-telegram   Author: friendly-telegram   File: heroku.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, **kwargs):
        super().__init__(**kwargs)
        if "heroku_api_token" in os.environ:
            # This is called before asyncio is even set up. We can only use sync methods which is fine.
            api_token = collections.namedtuple("api_token", ["ID", "HASH"])(os.environ["api_id"],
                                                                            os.environ["api_hash"])
            app, config = heroku.get_app([c[1] for c in self.client_data],
                                         os.environ["heroku_api_token"], api_token, False, True)
            if os.environ["DYNO"].startswith("web."):
                app.scale_formation_process("worker-DO-NOT-TURN-ON-OR-THINGS-WILL-BREAK", 0)
            atexit.register(functools.partial(exit_handler, app)) 
Example 25
Project: friendly-telegram   Author: friendly-telegram   File: updater.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def register(cb):
    cb(UpdaterMod()) 
Example 26
Project: friendly-telegram   Author: friendly-telegram   File: updater.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def restart_common(self, message):
        await self.prerestart_common(message)
        atexit.register(restart)
        [handler] = logging.getLogger().handlers
        handler.setLevel(logging.CRITICAL)
        for client in self.allclients:
            # Terminate main loop of all running clients
            # Won't work if not all clients are ready
            if client is not message.client:
                await client.disconnect()
        await message.client.disconnect() 
Example 27
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def tmpdir(prefix='npythy_tempdir_', delete=True):
    '''
    tmpdir() creates a temporary directory and yields its path. At python exit, the directory and
      all of its contents are recursively deleted (so long as the the normal python exit process is
      allowed to call the atexit handlers).
    tmpdir(prefix) uses the given prefix in the tempfile.mkdtemp() call.
    
    The option delete may be set to False to specify that the tempdir should not be deleted on exit.
    '''
    path = tempfile.mkdtemp(prefix=prefix)
    if not os.path.isdir(path): raise ValueError('Could not find or create temp directory')
    if delete: atexit.register(shutil.rmtree, path)
    return path 
Example 28
Project: neuropythy   Author: noahbenson   File: filemap.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def setup_cache_deletion(cache_path, actual_cache_path, cache_delete):
        '''
        The filemap.setup_cache_deletion requirement ensures that the cache directory will be
        deleted at system exit, if required.
        '''
        if cache_delete is True and cache_path is actual_cache_path:
            atexit.register(shutil.rmtree, cache_path)
        return True 
Example 29
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def cache_root(custom_directory):
        '''
        dataset.cache_root is the root directory in which the given dataset has been cached.
        '''
        if custom_directory is not None: return None
        elif config['data_cache_root'] is None:
            # we create a data-cache in a temporary directory
            path = tempfile.mkdtemp(prefix='npythy_data_cache_')
            if not os.path.isdir(path): raise ValueError('Could not find or create cache directory')
            config['data_cache_root'] = path
            atexit.register(shutil.rmtree, path)
        return config['data_cache_root'] 
Example 30
Project: soccer-matlab   Author: utra-robosoccer   File: logz.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def configure_output_dir(d=None):
    """
    Set output directory to d, or to /tmp/somerandomnumber if d is None
    """
    G.first_row = True
    G.log_headers = []
    G.log_current_row = {}
    
    G.output_dir = d or "/tmp/experiments/%i"%int(time.time())
    if not osp.exists(G.output_dir):
        os.makedirs(G.output_dir)
    G.output_file = open(osp.join(G.output_dir, "log.txt"), 'w')
    atexit.register(G.output_file.close)
    print(colorize("Logging data to %s"%G.output_file.name, 'green', bold=True))