Python atexit.register() Examples

The following are 30 code examples of atexit.register(). 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 atexit , or try the search function .
Example #1
Source File: environments.py    From holodeck with 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 #2
Source File: weakref.py    From aegea with 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 #3
Source File: wrappers.py    From soccer-matlab with 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
Source File: wrappers.py    From soccer-matlab with 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
Source File: regrtest.py    From jawfish with 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
Source File: concurrency.py    From dataflow with 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
Source File: manager.py    From verge3d-blender-addon with 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
Source File: profilehooks.py    From verge3d-blender-addon with 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
Source File: profilehooks.py    From verge3d-blender-addon with 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
Source File: profilehooks.py    From verge3d-blender-addon with 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
Source File: defs.py    From hadrian with 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
Source File: test_fixers.py    From misp42splunk with 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
Source File: rpc.py    From brownie with 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 #14
Source File: runner.py    From moler with 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 #15
Source File: __main__.py    From backend.ai-manager with 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 #16
Source File: handler.py    From calm-dsl with Apache License 2.0 5 votes vote down vote up
def connect(self):

        LOG.debug("Connecting to local DB")
        self.db.connect()
        atexit.register(self.close) 
Example #17
Source File: test_fixers.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_no_sys_import(self):
        b = """sys.exitfunc = f"""
        a = """atexit.register(f)"""
        msg = ("Can't find sys import; Please add an atexit import at the "
            "top of your file.")
        self.warns(b, a, msg) 
Example #18
Source File: test_fixers.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_in_a_function(self):
        b = """
            import sys
            def f():
                sys.exitfunc = func
            """
        a = """
            import sys
            import atexit
            def f():
                atexit.register(func)
             """
        self.check(b, a) 
Example #19
Source File: ca_certs_locater.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _update_temp_cert_file(temp_file, pem_texts):
    with open(temp_file, mode='w') as temp_cert_file:
        for pem_text in pem_texts:
            if len(pem_text) > 0:
                temp_cert_file.write(pem_text + '\n')
        temp_cert_file.flush()
    atexit.register(_do_safe_remove, temp_file) 
Example #20
Source File: logz.py    From soccer-matlab with 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)) 
Example #21
Source File: test_fixers.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_in_a_function(self):
        b = """
            import sys
            def f():
                sys.exitfunc = func
            """
        a = """
            import sys
            import atexit
            def f():
                atexit.register(func)
             """
        self.check(b, a) 
Example #22
Source File: test_fixers.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_names_import(self):
        b = """
            import sys, crumbs
            sys.exitfunc = my_func
            """
        a = """
            import sys, crumbs, atexit
            atexit.register(my_func)
            """
        self.check(b, a) 
Example #23
Source File: quitter.py    From qutebrowser with GNU General Public License v3.0 5 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 #24
Source File: conftest.py    From aioredis with MIT License 5 votes vote down vote up
def pytest_configure(config):
    bins = config.getoption('--redis-server')[:]
    cmd = 'which redis-server'
    if not bins:
        with os.popen(cmd) as pipe:
            path = pipe.read().rstrip()
        assert path, (
            "There is no redis-server on your computer."
            " Please install it first")
        REDIS_SERVERS[:] = [path]
    else:
        REDIS_SERVERS[:] = bins

    VERSIONS.update({srv: _read_server_version(srv)
                     for srv in REDIS_SERVERS})
    assert VERSIONS, ("Expected to detect redis versions", REDIS_SERVERS)

    class DynamicFixturePlugin:
        @pytest.fixture(scope='session',
                        params=REDIS_SERVERS,
                        ids=format_version)
        def server_bin(self, request):
            """Common for start_server and start_sentinel
            server bin path parameter.
            """
            return request.param
    config.pluginmanager.register(DynamicFixturePlugin(), 'server-bin-fixture')

    if config.getoption('--uvloop'):
        try:
            import uvloop
        except ImportError:
            raise RuntimeError(
                "Can not import uvloop, make sure it is installed")
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) 
Example #25
Source File: busybox.py    From pylxd with Apache License 2.0 5 votes vote down vote up
def create_busybox_image():
    busybox = Busybox()
    atexit.register(busybox.cleanup)

    path = busybox.create_tarball()

    with open(path, "rb") as fd:
        fingerprint = hashlib.sha256(fd.read()).hexdigest()

    return path, fingerprint 
Example #26
Source File: busybox.py    From pylxd with Apache License 2.0 5 votes vote down vote up
def create_busybox_image():
    busybox = Busybox()
    atexit.register(busybox.cleanup)

    path = busybox.create_tarball()

    with open(path, "rb") as fd:
        fingerprint = hashlib.sha256(fd.read()).hexdigest()

    return path, fingerprint 
Example #27
Source File: rpc.py    From brownie with MIT License 5 votes vote down vote up
def __init__(self) -> None:
        self._rpc: Any = None
        self._time_offset: int = 0
        self._snapshot_id: Union[int, Optional[bool]] = False
        self._reset_id: Union[int, bool] = False
        self._current_id: Union[int, bool] = False
        self._undo_lock = threading.Lock()
        self._undo_buffer: List = []
        self._redo_buffer: List = []
        atexit.register(self._at_exit) 
Example #28
Source File: test_wsgi_unix_socket.py    From cherrypy with 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 #29
Source File: readline.py    From daudin with MIT License 5 votes vote down vote up
def setupReadline(local):
    """Initialize the readline library and command history.

    @return: A C{bool} to indicate whether standard input is a terminal
        (and therefore interactive).
    """
    readline.parse_and_bind('tab: complete')
    readline.set_completer_delims(' \t\n')
    readline.set_completer(Completer(local).complete)

    # Readline code from https://docs.python.org/3.7/library/readline.html
    histfile = os.path.join(os.path.expanduser('~'), '.daudin_history')

    try:
        readline.read_history_file(histfile)
        historyLen = readline.get_current_history_length()
    except FileNotFoundError:
        open(histfile, 'wb').close()
        historyLen = 0

    try:
        readline.append_history_file
    except AttributeError:
        # We won't be able to save readline history. This can happen on
        # Python 3.5 at least - not sure why.
        pass
    else:
        import atexit

        def saveHistory(prevHistoryLen, histfile):
            newHistoryLen = readline.get_current_history_length()
            readline.set_history_length(1000)
            readline.append_history_file(newHistoryLen - prevHistoryLen,
                                         histfile)

        atexit.register(saveHistory, historyLen, histfile)

    return True 
Example #30
Source File: ca_certs_locater.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _update_temp_cert_file(temp_file, pem_texts):
    with open(temp_file, mode='w') as temp_cert_file:
        for pem_text in pem_texts:
            if len(pem_text) > 0:
                temp_cert_file.write(pem_text + '\n')
        temp_cert_file.flush()
    atexit.register(_do_safe_remove, temp_file)