python类format_exc()的实例源码

netpycos.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _tcp_proc(self, addrinfo, task=None):
        """
        Internal use only.
        """
        task.set_daemon()
        sock = addrinfo.tcp_sock
        while 1:
            try:
                conn, addr = yield sock.accept()
            except ssl.SSLError as err:
                logger.debug('SSL connection failed: %s', str(err))
                continue
            except GeneratorExit:
                break
            except:
                logger.debug(traceback.format_exc())
                continue
            SysTask(self._tcp_conn_proc, conn, addrinfo)
pipe_grep.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def line_reader(apipe, coro=None):
    nlines = 0
    while True:
        try:
            line = yield apipe.readline()
        except:
            asyncoro.logger.debug('read failed')
            asyncoro.logger.debug(traceback.format_exc())
            break
        nlines += 1
        if not line:
            break
        print(line.decode())
    raise StopIteration(nlines)

# asyncoro.logger.setLevel(asyncoro.Logger.DEBUG)
netpycos.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def peer_status(task):
        _Peer._lock.acquire()
        if isinstance(task, Task):
            # if there is another status_task, add or replace?
            for peer in _Peer.peers.itervalues():
                try:
                    task.send(PeerStatus(peer.location, peer.name, PeerStatus.Online))
                except:
                    logger.debug(traceback.format_exc())
                    break
            else:
                _Peer.status_task = task
        elif task is None:
            _Peer.status_task = None
        else:
            logger.warning('invalid peer status task ignored')
        _Peer._lock.release()
pipe_grep.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def line_reader(apipe, coro=None):
    nlines = 0
    while True:
        try:
            line = yield apipe.readline()
        except:
            asyncoro.logger.debug('read failed')
            asyncoro.logger.debug(traceback.format_exc())
            break
        nlines += 1
        if not line:
            break
        print(line.decode())
    raise StopIteration(nlines)

# asyncoro.logger.setLevel(asyncoro.Logger.DEBUG)
__init__.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 132 收藏 0 点赞 0 评论 0
def terminate(self):
            if hasattr(self.cmd_write, 'getsockname'):
                self.cmd_write.close()
            self.cmd_read.close()
            for fd in self._fds.itervalues():
                try:
                    self._poller.unregister(fd._fileno)
                except:
                    logger.warning('unregister of %s failed with %s',
                                   fd._fileno, traceback.format_exc())
                fd._notifier = None
            self._fds.clear()
            self._timeouts = []
            if hasattr(self._poller, 'terminate'):
                self._poller.terminate()
            self._poller = None
            self.cmd_read = self.cmd_write = None
netpycos.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def _tcp_proc(self, addrinfo, task=None):
        """
        Internal use only.
        """
        task.set_daemon()
        sock = addrinfo.tcp_sock
        while 1:
            try:
                conn, addr = yield sock.accept()
            except ssl.SSLError as err:
                logger.debug('SSL connection failed: %s', str(err))
                continue
            except GeneratorExit:
                break
            except:
                logger.debug(traceback.format_exc())
                continue
            SysTask(self._tcp_conn_proc, conn, addrinfo)
pipe_grep.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def line_reader(apipe, coro=None):
    nlines = 0
    while True:
        try:
            line = yield apipe.readline()
        except:
            asyncoro.logger.debug('read failed')
            asyncoro.logger.debug(traceback.format_exc())
            break
        nlines += 1
        if not line:
            break
        print(line.decode())
    raise StopIteration(nlines)

# asyncoro.logger.setLevel(asyncoro.Logger.DEBUG)
__init__.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def terminate(self):
            if hasattr(self.cmd_write, 'getsockname'):
                self.cmd_write.close()
            self.cmd_read.close()
            for fd in self._fds.values():
                try:
                    self._poller.unregister(fd._fileno)
                except:
                    logger.warning('unregister of %s failed with %s',
                                   fd._fileno, traceback.format_exc())
                fd._notifier = None
            self._fds.clear()
            self._timeouts = []
            if hasattr(self._poller, 'terminate'):
                self._poller.terminate()
            self._poller = None
            self.cmd_read = self.cmd_write = None
builder_base.py 文件源码 项目:rpwng 作者: MrNbaYoh 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def build(self, file):
        if self.built:
            raise PermissionError("You cannot build multiple times!")

        if not self.loaded:
            self.load(file)

        old = os.getcwd()
        sys.path.append(os.path.dirname(os.path.abspath(file)))  # for module import that aren't "include" call
        try:
            content = open(file, "rb").read()
            os.chdir(os.path.dirname(os.path.abspath(file)))  # set the current working directory, for open() etc.
            exec(compile(content, file, 'exec'), self.user_functions)
        except Exception as err:
            print("An exception occured while building: ", file=sys.stderr)
            lines = traceback.format_exc(None, err).splitlines()
            print("  " + lines[-1], file=sys.stderr)
            for l in lines[3:-1]:
                print(l, file=sys.stderr)
            exit(1)

        os.chdir(old)
        sys.path.remove(os.path.dirname(os.path.abspath(file)))
        self.built = True
builder_base.py 文件源码 项目:rpwng 作者: MrNbaYoh 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def load(self, file):
        if self.loaded:
            return

        sys.path.append(os.path.dirname(os.path.abspath(file)))  # for module import that aren't "include" call
        old = os.getcwd()
        try:
            content = open(file, "rb").read()
            os.chdir(os.path.dirname(os.path.abspath(file)))  # set the current working directory, for open() etc.
            exec(compile(content, file, 'exec'), self.user_functions)
        except Exception as err:
            print("An exception occured while loading: ", file=sys.stderr)
            lines = traceback.format_exc(None, err).splitlines()
            print("  " + lines[-1], file=sys.stderr)
            for l in lines[3:-1]:
                print(l, file=sys.stderr)
            exit(1)

        os.chdir(old)
        sys.path.remove(os.path.dirname(os.path.abspath(file)))
        self.loaded = True
        self.mem_offset = 0
base_modules.py 文件源码 项目:rpwng 作者: MrNbaYoh 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def include(self, incfile: str):

        old = self.current_path
        self.current_path = os.path.join(old, os.path.dirname(incfile))

        path = os.path.join(self.current_path, os.path.basename(incfile))
        sys.path.append(self.current_path)

        try:
            content = open(path, "rb").read()
            os.chdir(self.current_path)  # set the current working directory, for open() etc.
            exec(compile(content, path, 'exec'), self.user_functions)
        except Exception as err:
            print("An exception occured while building: ", file=sys.stderr)
            lines = traceback.format_exc(None, err).splitlines()
            print("  " + lines[-1], file=sys.stderr)
            for l in lines[3:-1]:
                print(l, file=sys.stderr)
            exit(1)

        sys.path.remove(self.current_path)
        os.chdir(old)
        self.current_path = old
gogen.py 文件源码 项目:python-driver 作者: bblfsh 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def generate2():
    """
    Call an external Python 2 program to retrieve the AST symbols of that
    language version
    :return:
    """
    import subprocess as sp
    import tempfile, shutil, sys, traceback

    tempdir = tempfile.mkdtemp()
    tempfile = os.path.join(tempdir, "py2_ast_code.py")

    py2_proc_out = ""
    try:
        with open(tempfile, 'w') as py2code:
            py2code.write(generate_str + WRITESYMS_CODE)

        py2_proc_out = sp.check_output(["python2", tempfile]).decode()
    finally:
        try:
            shutil.rmtree(tempdir)
        except:
            print("Warning: error trying to delete the temporal directory:", file=sys.stderr)
            print(traceback.format_exc(), file=sys.stderr)
    return set(py2_proc_out.splitlines())
req_install.py 文件源码 项目:python- 作者: secondtonone1 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def setup_py(self):
        assert self.source_dir, "No source dir for %s" % self
        try:
            import setuptools  # noqa
        except ImportError:
            if get_installed_version('setuptools') is None:
                add_msg = "Please install setuptools."
            else:
                add_msg = traceback.format_exc()
            # Setuptools is not available
            raise InstallationError(
                "Could not import setuptools which is required to "
                "install from a source distribution.\n%s" % add_msg
            )

        setup_py = os.path.join(self.setup_py_dir, 'setup.py')

        # Python2 __file__ should not be unicode
        if six.PY2 and isinstance(setup_py, six.text_type):
            setup_py = setup_py.encode(sys.getfilesystemencoding())

        return setup_py
web.py 文件源码 项目:docklet 作者: unias 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def internal_server_error(error):
    logger.error(error)
    logger.error(traceback.format_exc())
    if "username" in session:
        if "500" in session and "500_title" in session:
            reason = session['500']
            title = session['500_title']
            session.pop('500', None)
            session.pop('500_title', None)
        else:
            reason = '''The server encountered something unexpected that didn't allow it to complete the request. We apologize.You can go back to
<a href="/dashboard/">dashboard</a> or <a href="/logout">log out</a>'''
            title = 'Internal Server Error'
        return render_template('error/500.html', mysession = session, reason = reason, title = title)
    else:
        return redirect('/login/')
req_install.py 文件源码 项目:my-first-blog 作者: AnkurBegining 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def setup_py(self):
        assert self.source_dir, "No source dir for %s" % self
        try:
            import setuptools  # noqa
        except ImportError:
            if get_installed_version('setuptools') is None:
                add_msg = "Please install setuptools."
            else:
                add_msg = traceback.format_exc()
            # Setuptools is not available
            raise InstallationError(
                "Could not import setuptools which is required to "
                "install from a source distribution.\n%s" % add_msg
            )

        setup_py = os.path.join(self.setup_py_dir, 'setup.py')

        # Python2 __file__ should not be unicode
        if six.PY2 and isinstance(setup_py, six.text_type):
            setup_py = setup_py.encode(sys.getfilesystemencoding())

        return setup_py
bslurp.py 文件源码 项目:openstack-deploy 作者: yaoice 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def main():
    argument_spec = dict(
        compress=dict(default=True, type='bool'),
        dest=dict(type='str'),
        mode=dict(default='0644', type='str'),
        sha1=dict(default=None, type='str'),
        src=dict(required=True, type='str')
    )
    module = AnsibleModule(argument_spec)

    dest = module.params.get('dest')

    try:
        if dest:
            copy_to_host(module)
        else:
            copy_from_host(module)
    except Exception:
        module.exit_json(failed=True, changed=True,
                         msg=repr(traceback.format_exc()))


# import module snippets
os_sanity.py 文件源码 项目:openstack-deploy 作者: yaoice 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def main():
    module = AnsibleModule(
        argument_spec=openstack_full_argument_spec(
            password=dict(required=True,  no_log=True, type='str'),
            project=dict(required=True, type='str'),
            role=dict(required=True, type='str'),
            user=dict(required=True, type='str'),
            service=dict(required=True, type='str'),
        )
    )

    try:
        changed = True
        cloud = shade.operator_cloud(**module.params)

        getattr(SanityChecks, module.params.pop("service"))(cloud)

        module.exit_json(changed=changed)
    except Exception:
        module.exit_json(failed=True, changed=True,
                         msg=repr(traceback.format_exc()))

# import module snippets
Manager.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def __init__(self, resource=None ):
        self._mgr_lock = threading.Lock()
        self._ecm = None
        self._logger = logging.getLogger("ossie.events.Manager")
        self._logger.setLevel(logging.INFO)
        self._allow = True
        self._registrations=[]
        if resource :
            try:
                self._logger.debug("Requesting Domain Manager Access....")
                dom = resource.getDomainManager()
                self._logger.debug("Requesting EventChannelManager Access....")
                self._ecm  = dom.getRef()._get_eventChannelMgr()
                self._logger.debug("Acquired reference to EventChannelManager")
            except:
                #print traceback.format_exc()
                self._logger.warn("EventChannelManager - unable to resolve DomainManager's EventChannelManager ")
                pass
Manager.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def Subscriber(self, channel_name, registrationId=""):

        self._mgr_lock.acquire()
        self._logger.debug("Requesting Subscriber for Channel:" + str(channel_name) )
        sub = None
        try:
            if self._ecm:
                ereg = EventChannelManager.EventRegistration( channel_name = channel_name, reg_id = registrationId)

                self._logger.debug("Requesting Channel:" + str(channel_name) + " from Domain's EventChannelManager ")
                registration = self._ecm.registerResource( ereg )

                sub = EM_Subscriber( self, registration )

                self._logger.debug("Channel:" + str(channel_name) + " Reg-Id:" + str(registration.reg.reg_id))

                self._registrations.append( registration )

        except:
            #print traceback.format_exc()
            self._logger.error("Unable to create Subscriber for Channel:" + str(channel_name ))
        finally:
            self._mgr_lock.release()

        return sub
jobs.py 文件源码 项目:jobs 作者: josiahcarlson 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def maker(name):
        my_level = getattr(logging, name.upper()) if name != 'exception' else logging.ERROR
        altname = (name if name != 'exception' else 'error').upper()
        def _log(self, msg, *args, **kwargs):
            exc = kwargs.pop('exc_info', None) or name == 'exception'
            tb = ('\n' + traceback.format_exc().strip()) if exc else ''
            if args:
                try:
                    msg = msg % args
                except:
                    self.exception(
                        "Exception raised while formatting message:\n%s\n%r",
                        msg, args)
            msg += tb
            # todo: check level before printing
            if self.level <= my_level:
                print("%s %s %s"%(time.asctime(), altname, msg))
        _log.__name__ = name
        return _log
reduction.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _serve():
    from .util import is_exiting, sub_warning

    while 1:
        try:
            conn = _listener.accept()
            handle_wanted, destination_pid = conn.recv()
            _cache.remove(handle_wanted)
            send_handle(conn, handle_wanted, destination_pid)
            close(handle_wanted)
            conn.close()
        except:
            if not is_exiting():
                import traceback
                sub_warning(
                    'thread for sharing handles raised exception :\n' +
                    '-'*79 + '\n' + traceback.format_exc() + '-'*79
                    )

#
# Functions to be used for pickling/unpickling objects with handles
#
event.py 文件源码 项目:cbapi-python 作者: carbonblack 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def run(self):
        log.debug("starting event registry thread")
        while True:
            callback, cb, event_type, event_data = self._callback_queue.get()

            kwargs = callback["kwargs"]
            kwargs["cb"] = cb
            kwargs["event_type"] = event_type
            kwargs["event_data"] = event_data

            try:
                callback["func"](*callback["args"], **kwargs)
            except Exception as e:
                with self._error_lock:
                    self._errors.append({"exception": traceback.format_exc(), "timestamp": time.time(),
                                         "callback_func": callback["func"].__name__,
                                         "event_type": event_type, "event_data": event_data})
rfclass.py 文件源码 项目:astrobase 作者: waqasbhatti 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def LOGEXCEPTION(message):
    if LOGGER:
        LOGGER.exception(message)
    else:
        print(
            '%sZ [EXC!]: %s\nexception was: %s' % (
                datetime.utcnow().isoformat(),
                message, format_exc()
                )
            )



#######################
## UTILITY FUNCTIONS ##
#######################

# Utility function to report best scores
# modified from a snippet taken from:
# http://scikit-learn.org/stable/auto_examples/model_selection/plot_randomized_search.html
k2hat.py 文件源码 项目:astrobase 作者: waqasbhatti 项目源码 文件源码 阅读 50 收藏 0 点赞 0 评论 0
def LOGEXCEPTION(message):
    if LOGGER:
        LOGGER.exception(message)
    else:
        print(
            '%sZ [EXC!]: %s\nexception was: %s' % (
                datetime.utcnow().isoformat(),
                message, format_exc()
                )
            )



########################
## COLUMN DEFINITIONS ##
########################

# LC column definitions
# the first elem is the column description, the second is the format to use when
# writing a CSV LC column, the third is the type to use when parsing a CSV LC
# column
hplc.py 文件源码 项目:astrobase 作者: waqasbhatti 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def LOGEXCEPTION(message):
    if LOGGER:
        LOGGER.exception(message)
    else:
        print(
            '%sZ [EXC!]: %s\nexception was: %s' % (
                datetime.utcnow().isoformat(),
                message, format_exc()
                )
            )



###################
## USEFUL CONFIG ##
###################

# used to find HATIDs
magnitudes.py 文件源码 项目:astrobase 作者: waqasbhatti 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def LOGEXCEPTION(message):
    if LOGGER:
        LOGGER.exception(message)
    else:
        print(
            '%sZ [EXC!]: %s\nexception was: %s' % (
                dtime.utcnow().isoformat(),
                message, format_exc()
                )
            )


###############################################
## MAGIC CONSTANTS FOR 2MASS TO COUSINS/SDSS ##
###############################################

# converting from JHK to BVRI
generation.py 文件源码 项目:astrobase 作者: waqasbhatti 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def LOGEXCEPTION(message):
    if LOGGER:
        LOGGER.exception(message)
    else:
        print(
            '%sZ [EXC!]: %s\nexception was: %s' % (
                datetime.utcnow().isoformat(),
                message, format_exc()
                )
            )


###################
## LOCAL IMPORTS ##
###################

# LC reading functions
plotbase.py 文件源码 项目:astrobase 作者: waqasbhatti 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def LOGEXCEPTION(message):
    if LOGGER:
        LOGGER.exception(message)
    else:
        print(
            '%sZ [EXC!]: %s\nexception was: %s' % (
                datetime.utcnow().isoformat(),
                message, format_exc()
                )
            )



###################
## LOCAL IMPORTS ##
###################
flares.py 文件源码 项目:astrobase 作者: waqasbhatti 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def LOGEXCEPTION(message):
    if LOGGER:
        LOGGER.exception(message)
    else:
        print(
            '%sZ [EXC!]: %s\nexception was: %s' % (
                datetime.utcnow().isoformat(),
                message, format_exc()
                )
            )



###########################
## FLARE MODEL FUNCTIONS ##
###########################
__init__.py 文件源码 项目:astrobase 作者: waqasbhatti 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def LOGEXCEPTION(message):
    if LOGGER:
        LOGGER.exception(message)
    else:
        print(
            '%sZ [EXC!]: %s\nexception was: %s' % (
                datetime.utcnow().isoformat(),
                message, format_exc()
                )
            )



########################
## SOME OTHER IMPORTS ##
########################


问题


面经


文章

微信
公众号

扫码关注公众号