Python atexit.register() Examples

The following are code examples for showing how to use atexit.register(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_fixers.py    GNU Lesser General Public License v3.0 7 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 2
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: serving.py    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 3
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: serving.py    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 4
Project: RaspberryPi-Mertracking   Author: MertArduino   File: mertracking.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, friendly_mode=True):
        self.friendly_mode = friendly_mode

        # changes to I2C address or frequency
       	self.mh = Adafruit_MotorHAT(0x6f)
        atexit.register(self.__turn_off_motors)

        # Stepper motor 1
        self.sm_x = self.mh.getStepper(200, 1)      # 200 steps/rev, motor port #1
        self.sm_x.setSpeed(5)                       # 5 RPM
        self.current_x_steps = 0

        # Stepper motor 2
        self.sm_y = self.mh.getStepper(200, 2)      # 200 steps/rev, motor port #2
        self.sm_y.setSpeed(5)                       # 5 RPM
        self.current_y_steps = 0

        # Relay
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(RELAY_PIN, GPIO.OUT)
        GPIO.output(RELAY_PIN, GPIO.LOW) 
Example 5
Project: flasky   Author: RoseOu   File: serving.py    MIT License 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 6
Project: flasky   Author: RoseOu   File: ssl_support.py    MIT License 6 votes vote down vote up
def get_win_certfile():
    global _wincerts
    if _wincerts is not None:
        return _wincerts.name

    try:
        from wincertstore import CertFile
    except ImportError:
        return None

    class MyCertFile(CertFile):
        def __init__(self, stores=(), certs=()):
            CertFile.__init__(self)
            for store in stores:
                self.addstore(store)
            self.addcerts(certs)
            atexit.register(self.close)

    _wincerts = MyCertFile(stores=['CA', 'ROOT'])
    return _wincerts.name 
Example 7
Project: soccer-matlab   Author: utra-robosoccer   File: wrappers.py    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 8
Project: soccer-matlab   Author: utra-robosoccer   File: wrappers.py    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 9
Project: sic   Author: Yanixos   File: weakref.py    GNU General Public License v3.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 10
Project: bigquerylayers   Author: smandaric   File: ssl_support.py    GNU General Public License v3.0 6 votes vote down vote up
def get_win_certfile():
    try:
        import wincertstore
    except ImportError:
        return None

    class CertFile(wincertstore.CertFile):
        def __init__(self):
            super(CertFile, self).__init__()
            atexit.register(self.close)

        def close(self):
            try:
                super(CertFile, self).close()
            except OSError:
                pass

    _wincerts = CertFile()
    _wincerts.addstore('CA')
    _wincerts.addstore('ROOT')
    return _wincerts.name 
Example 11
Project: keybow-python   Author: pimoroni   File: __init__.py    MIT License 6 votes vote down vote up
def setup(keymap=FULL):
    global _is_setup, spi, callbacks, pins, leds, buf, states
    if _is_setup:
        return
    _is_setup = True

    callbacks = [None for key in keymap]
    pins = [key[0] for key in keymap]
    leds = [key[1] for key in keymap]
    buf = [[0, 0, 0, 1.0] for key in keymap]
    states = [True for key in keymap]

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(pins, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    for pin in pins:
        GPIO.add_event_detect(pin, GPIO.BOTH, callback=_handle_keypress, bouncetime=1)

    spi = SpiDev()
    spi.open(0, 0)
    spi.max_speed_hz = 1000000

    atexit.register(_on_exit) 
Example 12
Project: AshsSDK   Author: thehappydinoa   File: ssl_support.py    MIT License 6 votes vote down vote up
def get_win_certfile():
    try:
        import wincertstore
    except ImportError:
        return None

    class CertFile(wincertstore.CertFile):
        def __init__(self):
            super(CertFile, self).__init__()
            atexit.register(self.close)

        def close(self):
            try:
                super(CertFile, self).close()
            except OSError:
                pass

    _wincerts = CertFile()
    _wincerts.addstore('CA')
    _wincerts.addstore('ROOT')
    return _wincerts.name 
Example 13
Project: RLBotPack   Author: RLBot   File: doms_runner.py    MIT License 6 votes vote down vote up
def start_rl_bot():
    global child_process
    global read_out
    global read_err
    if child_process:
        kill_proc_tree(child_process.pid)
    child_process = Popen(
        SUBPROCESS_COMMAND,
        stdin=PIPE,
        stdout=PIPE,
        stderr=PIPE,
        shell=True,
        cwd=SUBPROCESS_CWD,
    )
    atexit.register(lambda: child_process.kill())  # behave like a daemon
    read_out = threading.Thread(target=print_file, args=[child_process.stdout], daemon=True)
    read_out.start()
    read_err = threading.Thread(target=print_file, args=[child_process.stderr], daemon=True)
    read_err.start() 
Example 14
Project: RLBotPack   Author: RLBot   File: bakkes.py    MIT License 6 votes vote down vote up
def start_gui_subprocess():
    # Create a new process such that asyncio doesn't complain about not being in the main thread
    global read_out
    global read_err
    bakkes_repl_dir = os.path.dirname(os.path.realpath(__file__))

    repl_process = Popen(
        'python bakkes_repl.py --silent',
        stdin=PIPE,
        stdout=PIPE,
        stderr=PIPE,
        cwd=bakkes_repl_dir,
    )
    atexit.register(lambda: repl_process.kill())  # behave like a daemon
    read_out = threading.Thread(target=print_file, args=[repl_process.stdout], daemon=True)
    read_out.start()
    read_err = threading.Thread(target=print_file, args=[repl_process.stderr], daemon=True)
    read_err.start()
    return repl_process 
Example 15
Project: RLBotPack   Author: RLBot   File: slicer.py    MIT License 6 votes vote down vote up
def start_gui_subprocess(self):
        # Create a new process such that QT doesn't complain about not being in the main thread
        quicktracer_dir = os.path.dirname(os.path.realpath(__file__))

        self.child_process = Popen(
            'python slicer_gui.py',
            stdin=PIPE,
            stdout=PIPE,
            stderr=PIPE,
            cwd=quicktracer_dir,
        )
        atexit.register(lambda: self.child_process.kill())  # behave like a daemon
        self.read_out = threading.Thread(target=self.process_messages_from_gui, args=[self.child_process.stdout], daemon=True)
        self.read_out.start()
        self.read_err = threading.Thread(target=print_stderr, args=[self.child_process.stderr], daemon=True)
        self.read_err.start() 
Example 16
Project: bearables   Author: sandyjmacdonald   File: __init__.py    MIT License 6 votes vote down vote up
def _init(led_mode):
    global _t_poll, _bus, ADDR

    if _bus is not None:
        return

    _bus = SMBus(i2c_bus_id())

    errors = 0

    for x in range(retries):
        try:
            _bus.write_byte_data(ADDR, 0b00000000, 0b00010000 + led_mode)
        except IOError:
            errors += 1
            time.sleep(0.001)

    if errors == retries:
        raise RuntimeError("Unable to communicate with badge!")

    _t_poll = Thread(target=_run)
    _t_poll.daemon = True
    _t_poll.start()

    atexit.register(_quit) 
Example 17
Project: openhatch   Author: campbe13   File: case.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def managed(cls, hostname=None, caller=None):
        hostname = hostname or socket.gethostname()
        if caller:
            hostname = ".".join([get_full_cls_name(caller), hostname])
        else:
            hostname += str(cls.next_worker_id())
        worker = cls(hostname)
        worker.ensure_started()
        stack = traceback.format_stack()

        @atexit.register
        def _ensure_shutdown_once():
            if not worker._shutdown_called:
                say("-- Found worker not stopped at shutdown: %s\n%s" % (
                        worker.hostname,
                        "\n".join(stack)))
                worker.ensure_shutdown()

        return worker 
Example 18
Project: openhatch   Author: campbe13   File: worker.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def run_worker(self):
        if self.pidfile:
            pidlock = platforms.create_pidlock(self.pidfile).acquire()
            atexit.register(pidlock.release)
        worker = self.WorkController(app=self.app,
                                concurrency=self.concurrency,
                                loglevel=self.loglevel,
                                logfile=self.logfile,
                                hostname=self.hostname,
                                ready_callback=self.on_consumer_ready,
                                embed_clockservice=self.run_clockservice,
                                schedule_filename=self.schedule,
                                scheduler_cls=self.scheduler_cls,
                                send_events=self.events,
                                db=self.db,
                                max_tasks_per_child=self.max_tasks_per_child,
                                task_time_limit=self.task_time_limit,
                                task_soft_time_limit=self.task_soft_time_limit,
                                autoscale=self.autoscale,
                                pool_cls=self.pool)
        self.install_platform_tweaks(worker)
        worker.start() 
Example 19
Project: deb-python-cassandra-driver   Author: openstack   File: asyncorereactor.py    Apache License 2.0 6 votes vote down vote up
def __init__(self):
        self._pid = os.getpid()
        self._loop_lock = Lock()
        self._started = False
        self._shutdown = False

        self._thread = None

        self._timers = TimerManager()

        try:
            dispatcher = self._loop_dispatch_class()
            dispatcher.validate()
            log.debug("Validated loop dispatch with %s", self._loop_dispatch_class)
        except Exception:
            log.exception("Failed validating loop dispatch with %s. Using busy wait execution instead.", self._loop_dispatch_class)
            dispatcher.close()
            dispatcher = _BusyWaitDispatcher()
        self._loop_dispatcher = dispatcher

        atexit.register(partial(_cleanup, weakref.ref(self))) 
Example 20
Project: jawfish   Author: war-and-code   File: regrtest.py    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 21
Project: Caffe-Python-Data-Layer   Author: liuxianming   File: TripletDataLayer.py    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 22
Project: alfred-yubikey-otp   Author: robertoriv   File: util.py    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 23
Project: pyblish-win   Author: pyblish   File: test_fixers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_simple(self):
        b = """
            import sys
            sys.exitfunc = my_atexit
            """
        a = """
            import sys
            import atexit
            atexit.register(my_atexit)
            """
        self.check(b, a) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_fixers.py    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 25
Project: pyblish-win   Author: pyblish   File: test_fixers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_complex_expression(self):
        b = """
            import sys
            sys.exitfunc = do(d)/a()+complex(f=23, g=23)*expression
            """
        a = """
            import sys
            import atexit
            atexit.register(do(d)/a()+complex(f=23, g=23)*expression)
            """
        self.check(b, a) 
Example 26
Project: pyblish-win   Author: pyblish   File: test_fixers.py    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 27
Project: pyblish-win   Author: pyblish   File: test_atexit.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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") 
Example 28
Project: pyblish-win   Author: pyblish   File: test_atexit.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_badargs(self):
        atexit.register(lambda: 1, 0, 0, (x for x in (1,2)), 0, 0)
        self.assertRaises(TypeError, atexit._run_exitfuncs) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_atexit.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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") 
Example 30
Project: pyblish-win   Author: pyblish   File: test_atexit.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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") 
Example 31
Project: pyblish-win   Author: pyblish   File: test_atexit.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_raise(self):
        atexit.register(self.raise1)
        atexit.register(self.raise2)
        self.assertRaises(TypeError, atexit._run_exitfuncs)

    ### helpers 
Example 32
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: util.py    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 33
Project: wikilinks   Author: trovdimi   File: decorators.py    MIT License 5 votes vote down vote up
def __init__(self, func):
        self.func = func
        self.cache = None
        atexit.register(self.save)
        self.modified = False 
Example 34
Project: zmirror   Author: aploium   File: initialise.py    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 35
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: sqlitelockfile.py    MIT License 5 votes vote down vote up
def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = SQLiteLockFile('somefile')
        >>> lock = SQLiteLockFile('somefile', threaded=False)
        """
        LockBase.__init__(self, path, threaded, timeout)
        self.lock_file = unicode(self.lock_file)
        self.unique_name = unicode(self.unique_name)

        if SQLiteLockFile.testdb is None:
            import tempfile
            _fd, testdb = tempfile.mkstemp()
            os.close(_fd)
            os.unlink(testdb)
            del _fd, tempfile
            SQLiteLockFile.testdb = testdb

        import sqlite3
        self.connection = sqlite3.connect(SQLiteLockFile.testdb)

        c = self.connection.cursor()
        try:
            c.execute("create table locks"
                      "("
                      "   lock_file varchar(32),"
                      "   unique_name varchar(32)"
                      ")")
        except sqlite3.OperationalError:
            pass
        else:
            self.connection.commit()
            import atexit
            atexit.register(os.unlink, SQLiteLockFile.testdb) 
Example 36
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: initialise.py    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 37
Project: friendly-telegram   Author: friendly-telegram   File: updater.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def register(cb):
    cb(UpdaterMod()) 
Example 38
Project: friendly-telegram   Author: friendly-telegram   File: updater.py    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 39
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def setup_interactive_mode(histfile='.python_history', interact=False):
    """Setup interactive mode with tab completion, prompt color, and command history."""
    # tab completion
    if 'libedit' in readline.__doc__:   # Mac
        print('Please intall GNU readline by "sudo easy_install readline", '
              'the libedit readline has caveat that cmd history not showing well with color prompt.')
        readline.parse_and_bind("bind '\t' rl_complete")
    else:
        readline.parse_and_bind("C-o: operate-and-get-next")
        readline.parse_and_bind("tab: complete")
        # color prompt
        sys.ps1 = '\x01\x1b[1;34m\x02>>> \x01\x1b[0m\x02'
        sys.ps2 = '\x01\x1b[1;34m\x02... \x01\x1b[0m\x02'
    # command history
    if histfile:
        # with a histfile, cmd history is saved across sessions.
        # Note, the test case execution is also saved in history file.
        histfile = os.path.expanduser("~" + os.getlogin() + os.sep + histfile)
        readline.set_history_length(500)
        try:
            with UserPrivilege():
                readline.read_history_file(histfile)
        except IOError as e:  # [Errno 13] Permission denied
            print_warn(e)

        def write_history_file():
            try:
                with UserPrivilege():
                    readline.write_history_file(histfile)
            except IOError as ex:  # [Errno 13] Permission denied
                print_warn(ex)
        atexit.register(write_history_file)

    if interact:
        try:
            import IPython
            IPython.embed()
        except ImportError:
            print("Python interactive mode. Note, use ipython for more interactive support.\n")
            code.interact(local=locals()) 
Example 40
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def exit_handler(handler, *args, **kwargs):
    """Register an exit handler if it is not registered yet.
    The duplication checking is needed for object that can close and re-connect."""
    if (handler, args, kwargs) not in atexit._exithandlers:
        atexit.register(handler, *args, **kwargs) 
Example 41
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def setup_interactive_mode(histfile='.python_history', interact=False):
    """Setup interactive mode with tab completion, prompt color, and command history."""
    # tab completion
    if 'libedit' in readline.__doc__:   # Mac
        print('Please intall GNU readline by "sudo easy_install readline", '
              'the libedit readline has caveat that cmd history not showing well with color prompt.')
        readline.parse_and_bind("bind '\t' rl_complete")
    else:
        readline.parse_and_bind("C-o: operate-and-get-next")
        readline.parse_and_bind("tab: complete")
        # color prompt
        sys.ps1 = '\x01\x1b[1;34m\x02>>> \x01\x1b[0m\x02'
        sys.ps2 = '\x01\x1b[1;34m\x02... \x01\x1b[0m\x02'
    # command history
    if histfile:
        # with a histfile, cmd history is saved across sessions.
        # Note, the test case execution is also saved in history file.
        histfile = os.path.expanduser("~" + os.getlogin() + os.sep + histfile)
        readline.set_history_length(500)
        try:
            with UserPrivilege():
                readline.read_history_file(histfile)
        except IOError as e:  # [Errno 13] Permission denied
            print_warn(e)

        def write_history_file():
            try:
                with UserPrivilege():
                    readline.write_history_file(histfile)
            except IOError as ex:  # [Errno 13] Permission denied
                print_warn(ex)
        atexit.register(write_history_file)

    if interact:
        try:
            import IPython
            IPython.embed()
        except ImportError:
            print("Python interactive mode. Note, use ipython for more interactive support.\n")
            code.interact(local=locals()) 
Example 42
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def exit_handler(handler, *args, **kwargs):
    """Register an exit handler if it is not registered yet.
    The duplication checking is needed for object that can close and re-connect."""
    if (handler, args, kwargs) not in atexit._exithandlers:
        atexit.register(handler, *args, **kwargs) 
Example 43
Project: flasky   Author: RoseOu   File: initialise.py    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
    sys.stdout = wrapped_stdout = \
        wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
    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 44
Project: flasky   Author: RoseOu   File: initialise.py    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
    sys.stdout = wrapped_stdout = \
        wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
    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 45
Project: alfred-urban-dictionary   Author: xilopaint   File: util.py    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 46
Project: soccer-matlab   Author: utra-robosoccer   File: logz.py    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 47
Project: sic   Author: Yanixos   File: sqlitelockfile.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = SQLiteLockFile('somefile')
        >>> lock = SQLiteLockFile('somefile', threaded=False)
        """
        LockBase.__init__(self, path, threaded, timeout)
        self.lock_file = unicode(self.lock_file)
        self.unique_name = unicode(self.unique_name)

        if SQLiteLockFile.testdb is None:
            import tempfile
            _fd, testdb = tempfile.mkstemp()
            os.close(_fd)
            os.unlink(testdb)
            del _fd, tempfile
            SQLiteLockFile.testdb = testdb

        import sqlite3
        self.connection = sqlite3.connect(SQLiteLockFile.testdb)

        c = self.connection.cursor()
        try:
            c.execute("create table locks"
                      "("
                      "   lock_file varchar(32),"
                      "   unique_name varchar(32)"
                      ")")
        except sqlite3.OperationalError:
            pass
        else:
            self.connection.commit()
            import atexit
            atexit.register(os.unlink, SQLiteLockFile.testdb) 
Example 48
Project: sic   Author: Yanixos   File: initialise.py    GNU General Public License v3.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 49
Project: sic   Author: Yanixos   File: ssl_support.py    GNU General Public License v3.0 5 votes vote down vote up
def get_win_certfile():
    global _wincerts
    if _wincerts is not None:
        return _wincerts.name

    try:
        from wincertstore import CertFile
    except ImportError:
        return None

    class MyCertFile(CertFile):
        def __init__(self, stores=(), certs=()):
            CertFile.__init__(self)
            for store in stores:
                self.addstore(store)
            self.addcerts(certs)
            atexit.register(self.close)

        def close(self):
            try:
                super(MyCertFile, self).close()
            except OSError:
                pass

    _wincerts = MyCertFile(stores=['CA', 'ROOT'])
    return _wincerts.name 
Example 50
Project: i-portalen   Author: I-sektionen   File: grunt.py    MIT License 5 votes vote down vote up
def start_grunt(self):
        #  Only start the process once!
        if self.grunt_process is not None:
            return
        print('>>> Starting grunt! :)')
        self.grunt_process = subprocess.Popen(
            ['npm install {0}'.format(settings.BASE_DIR),
             'grunt --gruntfile={0}/Gruntfile.js --base=.'.format(settings.BASE_DIR)],
            shell=True,
        )
        print('>>> Gruntprocess on pid {0}'.format(self.grunt_process.pid))

        #  When this instance is killed/terminated also kill the subprocess.
        atexit.register(kill_grunt_process, self.grunt_process.pid)