Python atexit.register() Examples

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

Example 1
Project: kas   Author: siemens   File: kas.py    (license) View Source Project 8 votes vote down vote up
def kas(argv):
    """
        The main entry point of kas.
    """
    create_logger()

    parser = kas_get_argparser()
    args = parser.parse_args(argv)

    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)

    logging.info('%s %s started', os.path.basename(sys.argv[0]), __version__)

    loop = asyncio.get_event_loop()

    for sig in (signal.SIGINT, signal.SIGTERM):
        loop.add_signal_handler(sig, interruption)
    atexit.register(_atexit_handler)

    for plugin in getattr(kasplugin, 'plugins', []):
        if plugin().run(args):
            return

    parser.print_help() 
Example 2
Project: vcenter-exporter   Author: sapcc   File: vcenter-exporter.py    (Apache License 2.0) View Source Project 8 votes vote down vote up
def connect_to_vcenter(self):

        # connect to vcenter
        try:
            si = SmartConnect(
                host=self.configs['main']['host'],
                user=self.configs['main']['user'],
                pwd=self.configs['main']['password'],
                port=self.configs['main']['port'],
                sslContext=self.context)
            atexit.register(Disconnect, si)

        except IOError as e:
            logging.error("Could not connect to vcenter." + str(e))

        if not si:
            raise SystemExit("Unable to connect to host with supplied info.")

        return si 
Example 3
Project: rudra   Author: 7h3rAm   File: rudra.py    (license) View Source Project 8 votes vote down vote up
def interactive(self):
    utils.set_prompt(ps1="(rudra) ", ps2="... ")

    import os
    import readline
    import rlcompleter
    import atexit

    histfile = os.path.join(os.environ["HOME"], ".rudrahistory")
    if os.path.isfile(histfile):
      readline.read_history_file(histfile)
    atexit.register(readline.write_history_file, histfile)

    r = self
    print "Use the \"r\" object to analyze files"

    vars = globals()
    vars.update(locals())
    readline.set_completer(rlcompleter.Completer(vars).complete)
    readline.parse_and_bind("tab: complete")

    del os, histfile, readline, rlcompleter, atexit
    code.interact(banner="", local=vars) 
Example 4
Project: my-first-blog   Author: AnkurBegining   File: ssl_support.py    (license) View Source Project 7 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 5
Project: mongodb-monitoring   Author: jruaux   File: ssl_support.py    (Apache License 2.0) View Source Project 7 votes vote down vote up
def _load_wincerts():
        """Set _WINCERTS to an instance of wincertstore.Certfile."""
        global _WINCERTS

        certfile = CertFile()
        certfile.addstore("CA")
        certfile.addstore("ROOT")
        atexit.register(certfile.close)

        _WINCERTS = certfile

    # XXX: Possible future work.
    # - Support CRL files? Only supported by CPython >= 2.7.9 and >= 3.4
    #   http://bugs.python.org/issue8813
    # - OCSP? Not supported by python at all.
    #   http://bugs.python.org/issue17123
    # - Setting OP_NO_COMPRESSION? The server doesn't yet.
    # - Adding an ssl_context keyword argument to MongoClient? This might
    #   be useful for sites that have unusual requirements rather than
    #   trying to expose every SSLContext option through a keyword/uri
    #   parameter. 
Example 6
Project: python-   Author: secondtonone1   File: ssl_support.py    (license) View Source Project 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 7
Project: python-   Author: secondtonone1   File: weakref.py    (license) View Source Project 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 8
Project: twentybn-dl   Author: TwentyBN   File: extract.py    (MIT License) View Source Project 6 votes vote down vote up
def extract_chunks(files, num_images, out_path):
    with tqdm(total=num_images,
              unit='images',
              ncols=80,
              unit_scale=True) as pbar:
        process = tar(cat(files, _piped=True), 'xvz', _iter=True, _cwd=out_path)

        def kill():
            try:
                process.kill()
            except:
                pass
        atexit.register(kill)
        for line in process:
            if line.strip().endswith('.jpg'):
                pbar.update(1) 
Example 9
Project: twentybn-dl   Author: TwentyBN   File: network.py    (MIT License) View Source Project 6 votes vote down vote up
def get(self, url):
        print("Downloading: '{}'".format(url))
        try:
            process = sh.wget('-q',
                              '-c',
                              '--tries=3',
                              url,
                              _cwd=self.base,
                              _bg=True)

            def kill():
                try:
                    process.kill()
                except:
                    pass
            atexit.register(kill)
            process.wait()
            return DownloadResult(DOWNLOAD_SUCCESS, url, None)
        except Exception as e:
            return DownloadResult(DOWNLOAD_FAILURE, url, repr(self.e)) 
Example 10
Project: deb-python-cassandra-driver   Author: openstack   File: asyncorereactor.py    (Apache License 2.0) View Source Project 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 11
Project: Projects   Author: it2school   File: midi.py    (license) View Source Project 6 votes vote down vote up
def init():
    """initialize the midi module
    pygame.midi.init(): return None
    
    Call the initialisation function before using the midi module.
    
    It is safe to call this more than once.
    """
    global _init, _pypm
    if not _init:
        import pygame.pypm
        _pypm = pygame.pypm

        _pypm.Initialize()
        _init = True
        atexit.register(quit) 
Example 12
Project: Flask_Blog   Author: sugarguo   File: serving.py    (GNU General Public License v3.0) View Source Project 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 13
Project: Flask_Blog   Author: sugarguo   File: ssl_support.py    (GNU General Public License v3.0) View Source Project 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 14
Project: dpl   Author: ppengtang   File: layer.py    (MIT License) View Source Project 6 votes vote down vote up
def set_roidb(self, roidb):
        """Set the roidb to be used by this layer during training."""
        self._roidb = roidb
        self._shuffle_roidb_inds()
        if cfg.TRAIN.USE_PREFETCH:
            self._blob_queue = Queue(10)
            self._prefetch_process = BlobFetcher(self._blob_queue,
                                                 self._roidb,
                                                 self._num_classes)
            self._prefetch_process.start()
            # Terminate the child process when the parent exists
            def cleanup():
                print 'Terminating BlobFetcher'
                self._prefetch_process.terminate()
                self._prefetch_process.join()
            import atexit
            atexit.register(cleanup) 
Example 15
Project: mbootuz   Author: ckhung   File: mbootuz.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def mounted_at(dev='', loopback=''):
    df = subprocess.check_output(['df'])
    if dev:
	fn = dev[dev.rfind('/')+1:]
	dev_or_loop = dev
	m = re.search('^' + dev + r'\s.*\s(\S+)$', df, flags=re.MULTILINE)
    elif loopback:
	dev_or_loop = loopback
	fn = loopback[loopback.rfind('/')+1:]
	m = re.search(r'\s(/lib/live/\S*' + fn + ')$', df, flags=re.MULTILINE)
    else:
	sys.exit('mounted_at() needs at least one arg')
    if (m):
	return m.group(1)
    else:
        target_mp = '/tmp/mbootuz-' + str(os.getpid()) + '-' + fn
        subprocess.call(['mkdir', target_mp])
        try:
            subprocess.check_output(['mount', dev_or_loop, target_mp])
        except subprocess.CalledProcessError as e:
            subprocess.call(['rmdir', target_mp])
            sys.exit('mount failure [' + e.output +
                '], mbootuz aborted')
	atexit.register(cleanup, target_mp)
        return target_mp 
Example 16
Project: swjtu-pyscraper   Author: Desgard   File: serving.py    (MIT License) View Source Project 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 17
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: ssl_support.py    (MIT License) View Source Project 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 18
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: sqlitelockfile.py    (MIT License) View Source Project 6 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 19
Project: petronia   Author: groboclown   File: window_mapper.py    (license) View Source Project 6 votes vote down vote up
def _setup_window_style(self, info):
        if 'title' not in info:
            info['title'] = window__get_title(info['hwnd'])
        is_managed, remove_border, remove_title = self._get_managed_chrome_details(info)
        if is_managed:
            # print("DEBUG managed border {0}, title {1} for {2}".format(remove_border, remove_title, info))
            hwnd = info['hwnd']
            orig_size = window__border_rectangle(hwnd)
            orig_style = window__get_style(hwnd)
            self.__hwnd_restore_state[hwnd] = (orig_size, orig_style)
            # Always, always restore window state at exit.  This ensures it.
            atexit.register(_restore_window_state, hwnd, orig_size, orig_style)
            style_data = {}
            if remove_title:
                style_data['border'] = False
                style_data['dialog-frame'] = False
            if remove_border:
                style_data['size-border'] = False
            if len(style_data) > 0:
                try:
                    window__set_style(hwnd, style_data)
                except OSError as e:
                    self._log_debug("Problem setting style for {0}".format(info['class']), e)
                window__redraw(hwnd) 
Example 20
Project: adversarial-frcnn   Author: xiaolonw   File: layer.py    (license) View Source Project 6 votes vote down vote up
def set_roidb(self, roidb):
        """Set the roidb to be used by this layer during training."""
        self._roidb = roidb
        self._shuffle_roidb_inds()
        if cfg.TRAIN.USE_PREFETCH:
            self._blob_queue = Queue(10)
            self._prefetch_process = BlobFetcher(self._blob_queue,
                                                 self._roidb,
                                                 self._num_classes)
            self._prefetch_process.start()
            # Terminate the child process when the parent exists
            def cleanup():
                print 'Terminating BlobFetcher'
                self._prefetch_process.terminate()
                self._prefetch_process.join()
            import atexit
            atexit.register(cleanup) 
Example 21
Project: jira_worklog_scanner   Author: pgarneau   File: ssl_support.py    (license) View Source Project 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 22
Project: ave   Author: sonyxperiadev   File: performance.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def __init__(self, fn, skip=0, filename=None, immediate=False, dirs=False,
                 sort=None, entries=40):
        """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.dirs = dirs
        self.sort = sort or ('cumulative', 'time', 'calls')
        if isinstance(self.sort, str):
            self.sort = (self.sort, )
        self.entries = entries
        self.reset_stats()
        atexit.register(self.atexit) 
Example 23
Project: ave   Author: sonyxperiadev   File: performance.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def __init__(self, fn, skip=0, filename=None, immediate=False, dirs=False,
                 sort=None, entries=40):
        """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.dirs = dirs
        self.sort = sort or ('cumulative', 'time', 'calls')
        if isinstance(self.sort, str):
            self.sort = (self.sort, )
        self.entries = entries
        self.reset_stats()
        atexit.register(self.atexit) 
Example 24
Project: darkc0de-old-stuff   Author: tuwid   File: shell.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def autoCompletion(sqlShell=False, osShell=False):
    # First of all we check if the readline is available, by default
    # it is not in Python default installation on Windows
    if not readline.haveReadline:
        return

    if sqlShell:
        completer = CompleterNG(queriesForAutoCompletion())
    elif osShell:
        # TODO: add more operating system commands; differentiate commands
        # based on future operating system fingerprint
        completer = CompleterNG({
                                  "id": None, "ifconfig": None, "ls": None,
                                  "netstat -natu": None, "pwd": None,
                                  "uname": None, "whoami": None,
                                })

    readline.set_completer(completer.complete)
    readline.parse_and_bind("tab: complete")

    loadHistory()
    atexit.register(saveHistory) 
Example 25
Project: workflows.kyoyue   Author: wizyoung   File: workflow.py    (MIT License) View Source Project 6 votes vote down vote up
def register(self, name, serializer):
        """Register ``serializer`` object under ``name``.

        Raises :class:`AttributeError` if ``serializer`` in invalid.

        .. note::

            ``name`` will be used as the file extension of the saved files.

        :param name: Name to register ``serializer`` under
        :type name: ``unicode`` or ``str``
        :param serializer: object with ``load()`` and ``dump()``
            methods

        """
        # Basic validation
        getattr(serializer, 'load')
        getattr(serializer, 'dump')

        self._serializers[name] = serializer 
Example 26
Project: aiotasks   Author: cr0hn   File: backends.py    (license) View Source Project 6 votes vote down vote up
def __init__(self,
                 dsn: str,
                 loop,
                 prefix: str = "aiotasks"):

        AsyncTaskSubscribeRedis.__init__(self,
                                         dsn=dsn,
                                         prefix=prefix,
                                         loop=loop)
        AsyncTaskDelayRedis.__init__(self,
                                     dsn=dsn,
                                     prefix=prefix,
                                     loop=loop)
        AsyncTaskBase.__init__(self, dsn=dsn, loop=loop)

        # This line is necessary to close redis connections
        atexit.register(self.stop) 
Example 27
Project: fast-rcnn-distillation   Author: xiaolonw   File: layer.py    (license) View Source Project 6 votes vote down vote up
def set_roidb(self, roidb):
        """Set the roidb to be used by this layer during training."""
        self._roidb = roidb
        self._shuffle_roidb_inds()
        if cfg.TRAIN.USE_PREFETCH:
            self._blob_queue = Queue(10)
            self._prefetch_process = BlobFetcher(self._blob_queue,
                                                 self._roidb,
                                                 self._num_classes)
            self._prefetch_process.start()
            # Terminate the child process when the parent exists
            def cleanup():
                print 'Terminating BlobFetcher'
                self._prefetch_process.terminate()
                self._prefetch_process.join()
            import atexit
            atexit.register(cleanup) 
Example 28
Project: fast-rcnn-distillation   Author: xiaolonw   File: layer_pi.py    (license) View Source Project 6 votes vote down vote up
def set_roidb(self, roidb):
        """Set the roidb to be used by this layer during training."""
        self._roidb = roidb
        self._shuffle_roidb_inds()
        if cfg.TRAIN.USE_PREFETCH:
            self._blob_queue = Queue(10)
            self._prefetch_process = BlobFetcher(self._blob_queue,
                                                 self._roidb,
                                                 self._num_classes)
            self._prefetch_process.start()
            # Terminate the child process when the parent exists
            def cleanup():
                print 'Terminating BlobFetcher'
                self._prefetch_process.terminate()
                self._prefetch_process.join()
            import atexit
            atexit.register(cleanup) 
Example 29
Project: faster-rcnn-resnet   Author: Eniac-Xie   File: layer.py    (license) View Source Project 6 votes vote down vote up
def set_roidb(self, roidb):
        """Set the roidb to be used by this layer during training."""
        self._roidb = roidb
        self._shuffle_roidb_inds()
        if cfg.TRAIN.USE_PREFETCH:
            self._blob_queue = Queue(10)
            self._prefetch_process = BlobFetcher(self._blob_queue,
                                                 self._roidb,
                                                 self._num_classes)
            self._prefetch_process.start()
            # Terminate the child process when the parent exists
            def cleanup():
                print 'Terminating BlobFetcher'
                self._prefetch_process.terminate()
                self._prefetch_process.join()
            import atexit
            atexit.register(cleanup) 
Example 30
Project: zanph   Author: zanph   File: serving.py    (license) View Source Project 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 31
Project: routersploit   Author: reverse-shell   File: interpreter.py    (license) View Source Project 6 votes vote down vote up
def setup(self):
        """ Initialization of third-party libraries

        Setting interpreter history.
        Setting appropriate completer function.

        :return:
        """
        if not os.path.exists(self.history_file):
            open(self.history_file, 'a+').close()

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_length)
        atexit.register(readline.write_history_file, self.history_file)

        readline.parse_and_bind('set enable-keypad on')

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete") 
Example 32
Project: backports.weakref   Author: pjdelport   File: weakref.py    (license) View Source Project 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 33
Project: identifiera-sarkasm   Author: risnejunior   File: common_funs.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, filename, directory = "", header = [], delimiter='\t', clearFile=False, padding=0):
		self._header = ["[{:<{padding}}]".format(head, padding=padding) for head in header]
		self._filebacked = []
		self._buffer = []
		self._delimiter = delimiter
		self._file_path = os.path.join(directory, filename)
		self._padding = padding

		if directory and not (os.path.isdir(directory)):
			os.makedirs(directory)

		if os.path.isfile(self._file_path):
			with open(self._file_path, 'r', encoding='utf8') as file:
				self._filebacked = file.readlines()

		self._rewrite(clearFile)
		atexit.register(self.flush) 
Example 34
Project: Sci-Finder   Author: snverse   File: serving.py    (license) View Source Project 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 35
Project: Sci-Finder   Author: snverse   File: ssl_support.py    (license) View Source Project 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 36
Project: Sci-Finder   Author: snverse   File: serving.py    (license) View Source Project 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 37
Project: Sci-Finder   Author: snverse   File: ssl_support.py    (license) View Source Project 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 38
Project: purelove   Author: hucmosin   File: initialise.py    (license) View Source Project 6 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
    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 39
Project: purelove   Author: hucmosin   File: interpreter.py    (license) View Source Project 6 votes vote down vote up
def setup(self):
        """ Initialization of third-party libraries

        Setting interpreter history.
        Setting appropriate completer function.

        :return:
        """
        if not os.path.exists(self.history_file):
            open(self.history_file, 'a+').close()

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_length)
        atexit.register(readline.write_history_file, self.history_file)

        readline.parse_and_bind('set enable-keypad on')

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete") 
Example 40
Project: fourletter-phat   Author: pimoroni   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def setup():
    """Set up the display."""

    global _is_setup, display

    if _is_setup:
        return True

    display = AlphaNum4(i2c=bus)
    display.begin()
    display.clear()
    display.show()

    atexit.register(_exit)

    _is_setup = True 
Example 41
Project: miros   Author: aleph2c   File: KeyboardHit.py    (license) View Source Project 6 votes vote down vote up
def __init__(self):
        '''Creates a KBHit object that you can call to do various keyboard things.
        '''

        if os.name == 'nt':
            pass

        else:

            # Save the terminal settings
            self.fd = sys.stdin.fileno()
            self.new_term = termios.tcgetattr(self.fd)
            self.old_term = termios.tcgetattr(self.fd)

            # New terminal setting unbuffered
            self.new_term[3] = (self.new_term[3] & ~termios.ICANON & ~termios.ECHO)
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)

            # Support normal-terminal reset at exit
            atexit.register(self.set_normal_term) 
Example 42
Project: mouse   Author: boppreh   File: _nixcommon.py    (license) View Source Project 6 votes vote down vote up
def input_file(self):
        if self._input_file is None:
            try:
                self._input_file = open(self.path, 'rb')
            except IOError as e:
                if e.strerror == 'Permission denied':
                    print('Permission denied ({}). You must be sudo to access global events.'.format(self.path))
                    exit()

            def try_close():
                try:
                    self._input_file.close
                except:
                    pass
            atexit.register(try_close)
        return self._input_file 
Example 43
Project: harbour-sailfinder   Author: DylanVanAssche   File: serving.py    (license) View Source Project 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 44
Project: harbour-sailfinder   Author: DylanVanAssche   File: serving.py    (license) View Source Project 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 45
Project: vsphere-storage-for-docker   Author: vmware   File: vm_listener.py    (license) View Source Project 6 votes vote down vote up
def create_vm_powerstate_filter(pc, from_node):
    """
    Create a filter spec to list to VM power state changes
    """

    filterSpec = vmodl.query.PropertyCollector.FilterSpec()
    objSpec = vmodl.query.PropertyCollector.ObjectSpec(obj=from_node,
                                                       selectSet=vm_folder_traversal())
    filterSpec.objectSet.append(objSpec)
    # Add the property specs
    propSpec = vmodl.query.PropertyCollector.PropertySpec(type=vim.VirtualMachine, all=False)
    propSpec.pathSet.append(VM_POWERSTATE)
    filterSpec.propSet.append(propSpec)
    try:
        pcFilter = pc.CreateFilter(filterSpec, True)
        atexit.register(pcFilter.Destroy)
        return None
    except Exception as e:
        err_msg = "Problem creating PropertyCollector filter: {}".format(str(e))
        logging.error(err_msg)
        return err_msg 
Example 46
Project: vsphere-storage-for-docker   Author: vmware   File: vmdk_ops.py    (license) View Source Project 6 votes vote down vote up
def connectLocalSi():
    '''
	Initialize a connection to the local SI
	'''
    global _service_instance
    if not _service_instance:
        try:
            logging.info("Connecting to the local Service Instance as 'dcui' ")

            # Connect to local server as user "dcui" since this is the Admin that does not lose its
            # Admin permissions even when the host is in lockdown mode. User "dcui" does not have a
            # password - it is used by local application DCUI (Direct Console User Interface)
            # Version must be set to access newer features, such as VSAN.
            _service_instance = pyVim.connect.Connect(
                host='localhost',
                user='dcui',
                version=newestVersions.Get('vim'))
        except Exception as e:
            logging.exception("Failed to create the local Service Instance as 'dcui', continuing... : ")
            return

    # set out ID in context to be used in request - so we'll see it in logs
    reqCtx = VmomiSupport.GetRequestContext()
    reqCtx["realUser"] = 'dvolplug'
    atexit.register(pyVim.connect.Disconnect, _service_instance) 
Example 47
Project: GoToMeetingTools   Author: plongitudes   File: workflow.py    (license) View Source Project 6 votes vote down vote up
def register(self, name, serializer):
        """Register ``serializer`` object under ``name``.

        Raises :class:`AttributeError` if ``serializer`` in invalid.

        .. note::

            ``name`` will be used as the file extension of the saved files.

        :param name: Name to register ``serializer`` under
        :type name: ``unicode`` or ``str``
        :param serializer: object with ``load()`` and ``dump()``
            methods

        """
        # Basic validation
        getattr(serializer, 'load')
        getattr(serializer, 'dump')

        self._serializers[name] = serializer 
Example 48
Project: zeronet-debian   Author: bashrc   File: TorManager.py    (license) View Source Project 6 votes vote down vote up
def startTor(self):
        if sys.platform.startswith("win"):
            try:
                if not os.path.isfile(self.tor_exe):
                    self.downloadTor()

                self.log.info("Starting Tor client %s..." % self.tor_exe)
                tor_dir = os.path.dirname(self.tor_exe)
                self.tor_process = subprocess.Popen(r"%s -f torrc" % self.tor_exe, cwd=tor_dir, close_fds=True)
                for wait in range(1,10):  # Wait for startup
                    time.sleep(wait * 0.5)
                    self.enabled = True
                    if self.connect():
                        break
                # Terminate on exit
                atexit.register(self.stopTor)
            except Exception, err:
                self.log.error("Error starting Tor client: %s" % Debug.formatException(err))
                self.enabled = False
        return False 
Example 49
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 5 votes vote down vote up
def register(self):
        """RTI must be registered so it can be located.
        """
        if self._location:
            return -1
        if not inspect.isgeneratorfunction(self._method):
            return -1
        RTI._pycos._lock.acquire()
        if RTI._pycos._rtis.get(self._name, None) is None:
            RTI._pycos._rtis[self._name] = self
            RTI._pycos._lock.release()
            return 0
        else:
            RTI._pycos._lock.release()
            return -1 
Example 50
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 5 votes vote down vote up
def unregister(self):
        """Unregister registered RTI; see 'register' above.
        """
        if self._location:
            return -1
        RTI._pycos._lock.acquire()
        if RTI._pycos._rtis.pop(self._name, None) is None:
            RTI._pycos._lock.release()
            return -1
        else:
            RTI._pycos._lock.release()
            return 0