Python 2/3 compatible method for unregistering exit function.

    Python2 has no atexit.unregister function :/
167161
def atexit_unregister(func, *args, **kwargs):
    
    try:
        atexit.unregister(func, *args, **kwargs)
    except AttributeError:
        # This code runs in Python 2.7 *only*
        # Only replace with a noop, don't delete during iteration
        for i in range(len(atexit._exithandlers)):
            if atexit._exithandlers[i] == (func, args, kwargs):
                atexit._exithandlers[i] = (lambda: None, [], {})
                break
281489
def exit(self, status=0, message=None):
        
        if status:
            self.logger.error(message)
        if self.__parser__:  # pylint: disable-msg=E1101
            self.__parser__.exit(status, message)  # pylint: disable-msg=E1101
        else:
            sys.exit(status)
1183855
def unregister(self, entry_point):
        
        if entry_point not in self.registered_extensions:
            raise ValueError('Extension not registered')

        ep = EntryPoint.parse(entry_point)
        self.registered_extensions.remove(entry_point)
        if self._extensions_by_name is not None:
            del self._extensions_by_name[ep.name]
        for i, ext in enumerate(self.extensions):
            if ext.name == ep.name:
                del self.extensions[i]
                break
664103
def exit(self):
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((self.server2, self.port2))
        self._hello(sock)

        comms.send_message(sock, ("<Exit>" + self._get_token() + "</Exit>").encode())
        reply = comms.recv_message(sock)
        sock.close()
        ok, = struct.unpack('!I', reply)
        return ok != 0
568820
def abort(msg=None, exitcode=1):
    
    if msg is not None:
        if exitcode in (None, 0):
            print(msg)
        else:
            print_err(msg)
    sys.exit(exitcode)
163720
def atexit_register(func):
    
    try:
        import uwsgi

        orig = getattr(uwsgi, "atexit", None)

        def uwsgi_atexit():
            if callable(orig):
                orig()
            func()

        uwsgi.atexit = uwsgi_atexit
    except ImportError:
        atexit.register(func)
345069
def _exit_handler(self):
        

        # TODO: consider handling sys.stderr/sys.stdout exceptions related to
        # TODO (cont.): order of interpreter vs. subprocess shutdown signal receipt.
        # TODO (cont.): see https://bugs.python.org/issue11380


        # Make the cleanup file executable if it exists
        if os.path.isfile(self.cleanup_file):
            # Make the cleanup file self destruct.
            with open(self.cleanup_file, "a") as myfile:
                myfile.write("rm " + self.cleanup_file + "\n")
            os.chmod(self.cleanup_file, 0o755)

        # If the pipeline hasn't completed successfully, or already been marked
        # as failed, then mark it as failed now.

        if not self._has_exit_status:
            print("Pipeline status: {}".format(self.status))
            self.fail_pipeline(Exception("Pipeline failure. See details above."))

        if self.tee:
            self.tee.kill()
482345
def _exit_handling(self):
        

        def close_asyncio_loop():
            loop = None
            try:
                loop = asyncio.get_event_loop()
            except AttributeError:
                pass
            if loop is not None:
                loop.close()

        atexit.register(close_asyncio_loop)
275438
def fatal( callingClass, astr_key, **kwargs ):
    '''
    
    '''
    kwargs['exitToOS']  = True
    report( callingClass, astr_key, **kwargs )
54669
def _unregisterHandler(self, handler, shutdown=True):
        
        if handler in self._handlers:
            self._handlers.remove(handler)
            self._logger.removeHandler(handler)
            if shutdown:
                try:
                    handler.close()
                except KeyError:
                    # Depending on the Python version, it's possible for this call
                    # to fail most likely because some logging module objects get
                    # garbage collected before the VSGLogger object is.
                    pass
292649
def unregister(self, name, func):
        
        try:
            templatehook = self._registry[name]
        except KeyError:
            return

        templatehook.unregister(func)
185635
def unregister_handler(self, handler_or_func):
        
        index = -1
        for i, handler in enumerate(self._direct_handlers):
            if handler is handler_or_func or handler._original_func is handler_or_func:
                index = i
                break
        if index >= 0:
            self._direct_handlers.pop(index)
            self._cached_handlers = None

        elif self.parent_class_hook is not None and self.parent_class_hook.has_handler(handler_or_func):
            self.parent_class_hook.unregister_handler(handler_or_func)
            self._cached_handlers = None

        elif self.instance_class_hook is not None and self.instance_class_hook.has_handler(handler_or_func):
            self.instance_class_hook.unregister_handler(handler_or_func)
            self._cached_handlers = None

        else:
            raise ValueError('{} is not a registered handler of {}'.format(handler_or_func, self))
168759
def unregister(cls, plugin):
        
        plugs = getattr(cls, '_%s__plugins' % cls.__name__, {})
        try:
            plugs.pop(plugin.name())
        except AttributeError:
            pass
        except ValueError:
            pass
1329153
def shutdown(self, join=True, timeout=None):
        
        if self.is_alive():  # check if process started
            print("Shutdown initiated")
            self.exit.set()
            if join:
                self.join(timeout=timeout)
                # TODO : timeout before forcing terminate (SIGTERM)

        exitcode = self._process.exitcode if self._process else None  # we return None if the process was never started
        return exitcode
149468
def function_end(self):
        """"""
        self.newline_label(self.shared.function_name + "_exit", True, True)
        self.move("%14", "%15")
        self.pop("%14")
        self.newline_text("RET", True)
78140
def _chk_docopt_exit(self, args, exp_letters):
        """"""
        if args is None:
            args = sys.argv[1:]
        keys_all = self.exp_keys.union(self.exp_elems)
        if exp_letters:
            keys_all |= exp_letters
        unknown_args = self._chk_docunknown(args, keys_all)
        if unknown_args:
            raise RuntimeError("{USAGE}\n    **FATAL: UNKNOWN ARGS: {UNK}".format(
                USAGE=self.doc, UNK=" ".join(unknown_args)))
827011
def remove_handler(args):
    

    repo = _open_repo(args)
    anchor_id, anchor = _get_anchor(repo, args['<anchor-id>'])
    del repo[anchor_id]

    return ExitCode.OK