当前位置: 首页>>代码示例>>Python>>正文


Python atexit.register方法代码示例

本文整理汇总了Python中atexit.register方法的典型用法代码示例。如果您正苦于以下问题:Python atexit.register方法的具体用法?Python atexit.register怎么用?Python atexit.register使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在atexit的用法示例。


在下文中一共展示了atexit.register方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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 
开发者ID:kislyuk,项目名称:aegea,代码行数:18,代码来源:weakref.py

示例2: start

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:25,代码来源:wspbus.py

示例3: __init__

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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 
开发者ID:utra-robosoccer,项目名称:soccer-matlab,代码行数:24,代码来源:wrappers.py

示例4: replace_stdout

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:18,代码来源:regrtest.py

示例5: ensure_proc_terminate

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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)) 
开发者ID:tensorpack,项目名称:dataflow,代码行数:25,代码来源:concurrency.py

示例6: runServerProc

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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) 
开发者ID:Soft8Soft,项目名称:verge3d-blender-addon,代码行数:22,代码来源:manager.py

示例7: __init__

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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) 
开发者ID:Soft8Soft,项目名称:verge3d-blender-addon,代码行数:25,代码来源:profilehooks.py

示例8: __init__

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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) 
开发者ID:modelop,项目名称:hadrian,代码行数:22,代码来源:defs.py

示例9: test_comments

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:23,代码来源:test_fixers.py

示例10: _shutdown_2

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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)) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:20,代码来源:quitter.py

示例11: reset

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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 
开发者ID:eth-brownie,项目名称:brownie,代码行数:18,代码来源:rpc.py

示例12: __init__

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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)) 
开发者ID:nokia,项目名称:moler,代码行数:25,代码来源:runner.py

示例13: main

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:24,代码来源:__main__.py

示例14: generate_adhoc_ssl_context

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:20,代码来源:serving.py

示例15: __windows_start_process__

# 需要导入模块: import atexit [as 别名]
# 或者: from atexit import register [as 别名]
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") 
开发者ID:BYU-PCCL,项目名称:holodeck,代码行数:18,代码来源:environments.py


注:本文中的atexit.register方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。