Python traceback.print_exception() Examples

The following are code examples for showing how to use traceback.print_exception(). 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: jawfish   Author: war-and-code   File: __init__.py    MIT License 7 votes vote down vote up
def formatException(self, ei):
        """
        Format and return the specified exception information as a string.

        This default implementation just uses
        traceback.print_exception()
        """
        sio = io.StringIO()
        tb = ei[2]
        # See issues #9427, #1553375. Commented out for now.
        #if getattr(self, 'fullstack', False):
        #    traceback.print_stack(tb.tb_frame.f_back, file=sio)
        traceback.print_exception(ei[0], ei[1], tb, None, sio)
        s = sio.getvalue()
        sio.close()
        if s[-1:] == "\n":
            s = s[:-1]
        return s 
Example 2
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def handleError(self, record):
        """
        Handle errors which occur during an emit() call.

        This method should be called from handlers when an exception is
        encountered during an emit() call. If raiseExceptions is false,
        exceptions get silently ignored. This is what is mostly wanted
        for a logging system - most users will not care about errors in
        the logging system, they are more interested in application errors.
        You could, however, replace this with a custom handler if you wish.
        The record which was being processed is passed in to this method.
        """
        if raiseExceptions and sys.stderr:  # see issue 13807
            ei = sys.exc_info()
            try:
                traceback.print_exception(ei[0], ei[1], ei[2],
                                          None, sys.stderr)
                sys.stderr.write('Logged from file %s, line %s\n' % (
                                 record.filename, record.lineno))
            except IOError:
                pass    # see issue 5971
            finally:
                del ei 
Example 3
Project: pyblish-win   Author: pyblish   File: run.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def runcode(self, code):
        global interruptable
        try:
            self.usr_exc_info = None
            interruptable = True
            try:
                exec code in self.locals
            finally:
                interruptable = False
        except SystemExit:
            # Scripts that raise SystemExit should just
            # return to the interactive prompt
            pass
        except:
            self.usr_exc_info = sys.exc_info()
            if quitting:
                exit()
            print_exception()
            jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")
            if jit:
                self.rpchandler.interp.open_remote_stack_viewer()
        else:
            flush_stdout() 
Example 4
Project: kuaa   Author: rafaelwerneck   File: grid.py    GNU General Public License v3.0 6 votes vote down vote up
def run(self):
		while True:
			(cexp,gexp) = self.job_queue.get()
			if cexp is WorkerStopToken:
				self.job_queue.put((cexp,gexp))
				# print('worker {0} stop.'.format(self.name))
				break
			try:
				c, g = None, None
				if cexp != None:
					c = 2.0**cexp
				if gexp != None:
					g = 2.0**gexp
				rate = self.run_one(c,g)
				if rate is None: raise RuntimeError('get no rate')
			except:
				# we failed, let others do that and we just quit
			
				traceback.print_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])
				
				self.job_queue.put((cexp,gexp))
				sys.stderr.write('worker {0} quit.\n'.format(self.name))
				break
			else:
				self.result_queue.put((self.name,cexp,gexp,rate)) 
Example 5
Project: kuaa   Author: rafaelwerneck   File: grid.py    GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        while True:
            (cexp,gexp) = self.job_queue.get()
            if cexp is WorkerStopToken:
                self.job_queue.put((cexp,gexp))
                # print('worker {0} stop.'.format(self.name))
                break
            try:
                rate = self.run_one(2.0**cexp,2.0**gexp)
                if rate is None: raise RuntimeError("get no rate")
            except:
                # we failed, let others do that and we just quit
            
                traceback.print_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])
                
                self.job_queue.put((cexp,gexp))
                print('worker {0} quit.'.format(self.name))
                break
            else:
                self.result_queue.put((self.name,cexp,gexp,rate)) 
Example 6
Project: kuaa   Author: rafaelwerneck   File: grid.py    GNU General Public License v3.0 6 votes vote down vote up
def run(self):
		while True:
			(cexp,gexp) = self.job_queue.get()
			if cexp is WorkerStopToken:
				self.job_queue.put((cexp,gexp))
				# print('worker {0} stop.'.format(self.name))
				break
			try:
				c, g = None, None
				if cexp != None:
					c = 2.0**cexp
				if gexp != None:
					g = 2.0**gexp
				rate = self.run_one(c,g)
				if rate is None: raise RuntimeError('get no rate')
			except:
				# we failed, let others do that and we just quit
			
				traceback.print_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])
				
				self.job_queue.put((cexp,gexp))
				sys.stderr.write('worker {0} quit.\n'.format(self.name))
				break
			else:
				self.result_queue.put((self.name,cexp,gexp,rate)) 
Example 7
Project: Nurevam   Author: Maverun   File: events.py    MIT License 6 votes vote down vote up
def on_command_error(self,ctx,error):
        if self.bot.user.id == 181503794532581376 or self.error_log:
            print(error)
        if isinstance(error, commands.MissingRequiredArgument):
            await self.send_cmd_help(ctx)
        elif isinstance(error,commands.BadArgument):
            await self.send_cmd_help(ctx)
        elif isinstance(error, commands.CommandInvokeError):
            if isinstance(error.original,discord_error.Forbidden):
                await ctx.send("I am sorry, I need a certain permission to run it...")
                traceback.print_exception(type(error), error, error.__traceback__)
                return utils.prRed(type(error.original))
            errors = traceback.format_exception(type(error), error, error.__traceback__)
            Current_Time = datetime.datetime.utcnow().strftime("%b/%d/%Y %H:%M:%S UTC")
            utils.prRed(Current_Time)
            utils.prRed("Error!")
            traceback.print_exception(type(error), error, error.__traceback__)
            cog_error =  '```fix\nCogs:{0.command.cog_name}\tCommand:{0.command}\tAuthor:{0.message.author}-{0.message.author.id}\n' \
                         'Server:{0.message.guild.id}\n{0.message.clean_content}\nError:\n{1}```'.format(ctx,error)
            msg ="```py\n{}```\n{}\n```py\n{}\n```".format(Current_Time + "\n"+ "ERROR!",cog_error,"".join(errors).replace("`",""))
            if len(msg) >= 1900:
                msg = await utils.send_hastebin(msg)
            await self.bot.owner.send(msg or "There is no message but error...")
            await ctx.send("You either used the command incorrectly or an unexpected error occurred. A report has been sent to the creator so you can hope for a fix soon.") 
Example 8
Project: openhatch   Author: campbe13   File: log.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _safewrap_handlers(self):
        """Make the logger handlers dump internal errors to
        `sys.__stderr__` instead of `sys.stderr` to circumvent
        infinite loops."""

        def wrap_handler(handler):                  # pragma: no cover

            class WithSafeHandleError(logging.Handler):

                def handleError(self, record):
                    exc_info = sys.exc_info()
                    try:
                        try:
                            traceback.print_exception(exc_info[0],
                                                      exc_info[1],
                                                      exc_info[2],
                                                      None, sys.__stderr__)
                        except IOError:
                            pass    # see python issue 5971
                    finally:
                        del(exc_info)

            handler.handleError = WithSafeHandleError().handleError

        return map(wrap_handler, self.logger.handlers) 
Example 9
Project: jawfish   Author: war-and-code   File: __init__.py    MIT License 6 votes vote down vote up
def handleError(self, record):
        """
        Handle errors which occur during an emit() call.

        This method should be called from handlers when an exception is
        encountered during an emit() call. If raiseExceptions is false,
        exceptions get silently ignored. This is what is mostly wanted
        for a logging system - most users will not care about errors in
        the logging system, they are more interested in application errors.
        You could, however, replace this with a custom handler if you wish.
        The record which was being processed is passed in to this method.
        """
        if raiseExceptions and sys.stderr:  # see issue 13807
            ei = sys.exc_info()
            try:
                traceback.print_exception(ei[0], ei[1], ei[2],
                                          None, sys.stderr)
                sys.stderr.write('Logged from file %s, line %s\n' % (
                                 record.filename, record.lineno))
            except IOError: #pragma: no cover
                pass    # see issue 5971
            finally:
                del ei 
Example 10
Project: jawfish   Author: war-and-code   File: __init__.py    MIT License 6 votes vote down vote up
def emit(self, record):
        """
        Emit a record.

        If a formatter is specified, it is used to format the record.
        The record is then written to the stream with a trailing newline.  If
        exception information is present, it is formatted using
        traceback.print_exception and appended to the stream.  If the stream
        has an 'encoding' attribute, it is used to determine how to do the
        output to the stream.
        """
        try:
            msg = self.format(record)
            stream = self.stream
            stream.write(msg)
            stream.write(self.terminator)
            self.flush()
        except (KeyboardInterrupt, SystemExit): #pragma: no cover
            raise
        except:
            self.handleError(record) 
Example 11
Project: Repobot   Author: Desgard   File: formatters.py    MIT License 6 votes vote down vote up
def catch_format_error(method, self, *args, **kwargs):
    """show traceback on failed format call"""
    try:
        r = method(self, *args, **kwargs)
    except NotImplementedError:
        # don't warn on NotImplementedErrors
        return None
    except Exception:
        exc_info = sys.exc_info()
        ip = get_ipython()
        if ip is not None:
            ip.showtraceback(exc_info)
        else:
            traceback.print_exception(*exc_info)
        return None
    return self._check_return(r, args[0]) 
Example 12
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: futures.py    MIT License 6 votes vote down vote up
def __del__(self):
        # Do not run any checks if Python is shutting down.
        if not sys or not self._lock:
            return

        with self._lock:
            assert self._done or self._done is None
            exc_info = self._exc_info
            if exc_info and not self._observed:
                msg = 'Unobserved failed future'
                origin = self._origin
                if origin:
                    origin = '\n'.join(traceback.format_list(origin))
                    msg += ' originating from:\n\n{origin}\n\n'
                ptvsd.log.exception(msg, origin=origin, exc_info=exc_info)
                traceback.print_exception(*exc_info, file=sys.__stderr__) 
Example 13
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pycompletion.py    MIT License 6 votes vote down vote up
def GetImports(module_name):
    try:
        processor = pycompletionserver.Processor()
        data = urllib.unquote_plus(module_name)
        def_file, completions = _pydev_imports_tipper.GenerateTip(data)
        return processor.formatCompletionMessage(def_file, completions)
    except:
        s = StringIO.StringIO()
        exc_info = sys.exc_info()

        traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], limit=None, file=s)
        err = s.getvalue()
        pycompletionserver.dbg('Received error: ' + str(err), pycompletionserver.ERROR)
        raise


#=======================================================================================================================
# main
#======================================================================================================================= 
Example 14
Project: NiujiaoDebugger   Author: MrSrc   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def formatException(self, ei):
        """
        Format and return the specified exception information as a string.

        This default implementation just uses
        traceback.print_exception()
        """
        sio = io.StringIO()
        tb = ei[2]
        # See issues #9427, #1553375. Commented out for now.
        #if getattr(self, 'fullstack', False):
        #    traceback.print_stack(tb.tb_frame.f_back, file=sio)
        traceback.print_exception(ei[0], ei[1], tb, None, sio)
        s = sio.getvalue()
        sio.close()
        if s[-1:] == "\n":
            s = s[:-1]
        return s 
Example 15
Project: NiujiaoDebugger   Author: MrSrc   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def emit(self, record):
        """
        Emit a record.

        If a formatter is specified, it is used to format the record.
        The record is then written to the stream with a trailing newline.  If
        exception information is present, it is formatted using
        traceback.print_exception and appended to the stream.  If the stream
        has an 'encoding' attribute, it is used to determine how to do the
        output to the stream.
        """
        try:
            msg = self.format(record)
            stream = self.stream
            # issue 35046: merged two stream.writes into one.
            stream.write(msg + self.terminator)
            self.flush()
        except Exception:
            self.handleError(record) 
Example 16
Project: NiujiaoDebugger   Author: MrSrc   File: run.py    GNU General Public License v3.0 6 votes vote down vote up
def runcode(self, code):
        global interruptable
        try:
            self.usr_exc_info = None
            interruptable = True
            try:
                exec(code, self.locals)
            finally:
                interruptable = False
        except SystemExit:
            # Scripts that raise SystemExit should just
            # return to the interactive prompt
            pass
        except:
            self.usr_exc_info = sys.exc_info()
            if quitting:
                exit()
            # even print a user code SystemExit exception, continue
            print_exception()
            jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")
            if jit:
                self.rpchandler.interp.open_remote_stack_viewer()
        else:
            flush_stdout() 
Example 17
Project: NiujiaoDebugger   Author: MrSrc   File: unittestgui.py    GNU General Public License v3.0 6 votes vote down vote up
def discoverClicked(self):
        self.__rollbackImporter.rollbackImports()
        directory = self.getDirectoryToDiscover()
        if not directory:
            return
        self.directory_to_read = directory
        try:
            # Explicitly use 'None' value if no top level directory is
            # specified (indicated by empty string) as discover() explicitly
            # checks for a 'None' to determine if no tld has been specified
            top_level_dir = self.top_level_dir or None
            tests = unittest.defaultTestLoader.discover(directory, self.test_file_glob_pattern, top_level_dir)
            self.test_suite = tests
        except:
            exc_type, exc_value, exc_tb = sys.exc_info()
            traceback.print_exception(*sys.exc_info())
            self.errorDialog("Unable to run test '%s'" % directory,
                             "Error loading specified test: %s, %s" % (exc_type, exc_value))
            return
        self.notifyTestsDiscovered(self.test_suite)

    # Required callbacks 
Example 18
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: Utils.py    MIT License 6 votes vote down vote up
def addException():
	global errors
	#self.widget._report_exception()
	try:
		typ, val, tb = sys.exc_info()
		traceback.print_exception(typ, val, tb)
		if errors: errors.append("")
		exception = traceback.format_exception(typ, val, tb)
		errors.extend(exception)
		if len(errors) > 100:
			# If too many errors are found send the error report
			ReportDialog(self.widget)
	except:
		say(str(sys.exc_info()))

#=============================================================================== 
Example 19
Project: discord.py   Author: Rapptz   File: bot.py    MIT License 6 votes vote down vote up
def on_command_error(self, context, exception):
        """|coro|

        The default command error handler provided by the bot.

        By default this prints to :data:`sys.stderr` however it could be
        overridden to have a different implementation.

        This only fires if you do not specify any listeners for command error.
        """
        if self.extra_events.get('on_command_error', None):
            return

        if hasattr(context.command, 'on_error'):
            return

        cog = context.cog
        if cog:
            if Cog._get_overridden_method(cog.cog_command_error) is not None:
                return

        print('Ignoring exception in command {}:'.format(context.command), file=sys.stderr)
        traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)

    # global check registration 
Example 20
Project: pg2xls   Author: CarlosCorreiaM16e   File: pg2xls.py    GNU General Public License v3.0 6 votes vote down vote up
def get_password( username ):
    try:
        f = open( '%s/.pgpass' % os.environ[ 'HOME' ], "r" )
        lines = f.readlines()
        f.close()
        for l in lines:
            flds = l.split( ':' )
            if username == flds[ 3 ]:
                password = flds[ 4 ].strip()
                break

    except:
        t, v, tb = sys.exc_info()
        traceback.print_exception( t, v, tb )
        password = raw_input( 'Password: ' )
    return password


#------------------------------------------------------------------
# main 
Example 21
Project: key-vault-python-authentication   Author: Azure-Samples   File: key_vault_sample_base.py    MIT License 6 votes vote down vote up
def keyvaultsample(f):
    """
    decorator function for marking key vault sample methods
    """
    def wrapper(self):
        try:
            print('--------------------------------------------------------------------')
            print('RUNNING: {}'.format(f.__name__))
            print('--------------------------------------------------------------------')
            self.setup_sample()
            f(self)
        except Exception as e:
            print('ERROR: running sample failed with raised exception:')
            traceback.print_exception(type(e), e, getattr(e, '__traceback__', None))
            _failed.append(f.__name__)
    wrapper.__name__ = f.__name__
    wrapper.__doc__ = f.__doc__
    wrapper.kv_sample = True
    return wrapper 
Example 22
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def formatException(self, ei):
        """
        Format and return the specified exception information as a string.

        This default implementation just uses
        traceback.print_exception()
        """
        sio = cStringIO.StringIO()
        traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
        s = sio.getvalue()
        sio.close()
        if s[-1:] == "\n":
            s = s[:-1]
        return s 
Example 23
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def emit(self, record):
        """
        Emit a record.

        If a formatter is specified, it is used to format the record.
        The record is then written to the stream with a trailing newline.  If
        exception information is present, it is formatted using
        traceback.print_exception and appended to the stream.  If the stream
        has an 'encoding' attribute, it is used to determine how to do the
        output to the stream.
        """
        try:
            msg = self.format(record)
            stream = self.stream
            fs = "%s\n"
            if not _unicode: #if no unicode support...
                stream.write(fs % msg)
            else:
                try:
                    if (isinstance(msg, unicode) and
                        getattr(stream, 'encoding', None)):
                        ufs = u'%s\n'
                        try:
                            stream.write(ufs % msg)
                        except UnicodeEncodeError:
                            #Printing to terminals sometimes fails. For example,
                            #with an encoding of 'cp1251', the above write will
                            #work if written to a stream opened or wrapped by
                            #the codecs module, but fail when writing to a
                            #terminal even when the codepage is set to cp1251.
                            #An extra encoding step seems to be needed.
                            stream.write((ufs % msg).encode(stream.encoding))
                    else:
                        stream.write(fs % msg)
                except UnicodeError:
                    stream.write(fs % msg.encode("UTF-8"))
            self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record) 
Example 24
Project: pyblish-win   Author: pyblish   File: Tkinter.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def report_callback_exception(self, exc, val, tb):
        """Report callback exception on sys.stderr.

        Applications may want to override this internal function, and
        should when sys.stderr is None."""
        import traceback, sys
        print >>sys.stderr, "Exception in Tkinter callback"
        sys.last_type = exc
        sys.last_value = val
        sys.last_traceback = tb
        traceback.print_exception(exc, val, tb) 
Example 25
Project: pyblish-win   Author: pyblish   File: doctest.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _exception_traceback(exc_info):
    """
    Return a string containing a traceback message for the given
    exc_info tuple (as returned by sys.exc_info()).
    """
    # Get a traceback message.
    excout = StringIO()
    exc_type, exc_val, exc_tb = exc_info
    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
    return excout.getvalue()

# Override some StringIO methods. 
Example 26
Project: flasky   Author: RoseOu   File: basecommand.py    MIT License 5 votes vote down vote up
def format_exc(exc_info=None):
    if exc_info is None:
        exc_info = sys.exc_info()
    out = StringIO()
    traceback.print_exception(*exc_info, **dict(file=out))
    return out.getvalue() 
Example 27
Project: flasky   Author: RoseOu   File: doctest.py    MIT License 5 votes vote down vote up
def _exception_traceback(exc_info):
    """
    Return a string containing a traceback message for the given
    exc_info tuple (as returned by sys.exc_info()).
    """
    # Get a traceback message.
    excout = StringIO()
    exc_type, exc_val, exc_tb = exc_info
    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
    return excout.getvalue()

# Override some StringIO methods. 
Example 28
Project: flasky   Author: RoseOu   File: cmdline.py    MIT License 5 votes vote down vote up
def main(argv=None):
    """The main entry point to Coverage.

    This is installed as the script entry point.

    """
    if argv is None:
        argv = sys.argv[1:]
    try:
        start = time.clock()
        status = CoverageScript().command_line(argv)
        end = time.clock()
        if 0:
            print("time: %.3fs" % (end - start))
    except ExceptionDuringRun:
        # An exception was caught while running the product code.  The
        # sys.exc_info() return tuple is packed into an ExceptionDuringRun
        # exception.
        _, err, _ = sys.exc_info()
        traceback.print_exception(*err.args)
        status = ERR
    except CoverageException:
        # A controlled error inside coverage.py: print the message to the user.
        _, err, _ = sys.exc_info()
        print(err)
        status = ERR
    except SystemExit:
        # The user called `sys.exit()`.  Exit with their argument, if any.
        _, err, _ = sys.exc_info()
        if err.args:
            status = err.args[0]
        else:
            status = None
    return status 
Example 29
Project: python-sii   Author: voipir   File: shell.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __exit__(self, etype, evalue, etraceback):
        if any([etype, evalue, etraceback]):
            traceback.print_exception(etype, evalue, etraceback)
        os.chdir(self._olddir) 
Example 30
Project: lichess-bot   Author: ShailChoksi   File: lichess-bot.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def watch_control_stream(control_queue, li):
    response = li.get_event_stream()
    try:
        for line in response.iter_lines():
            if line:
                event = json.loads(line.decode('utf-8'))
                control_queue.put_nowait(event)
            else:
                control_queue.put_nowait({"type": "ping"})
    except (RemoteDisconnected, ChunkedEncodingError, ConnectionError, ProtocolError) as exception:
        logger.error("Terminating client due to connection error")
        traceback.print_exception(type(exception), exception, exception.__traceback__)
        control_queue.put_nowait({"type": "terminated"}) 
Example 31
Project: reportengine   Author: NNPDF   File: app.py    GNU General Public License v2.0 5 votes vote down vote up
def excepthook(self, etype, evalue, tb):
        print("\n----\n")
        print(colors.color_exception(etype, evalue, tb), file=sys.stderr)
        print("----\n")

        fd,name = tempfile.mkstemp(prefix=self.name + '-crash-', text=True)
        with os.fdopen(fd, 'w') as f:
            traceback.print_exception(etype, evalue, tb, file=f)



        root_log.critical(self.critical_message, colors.t.blue(name)) 
Example 32
Project: openhatch   Author: campbe13   File: timer2.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def apply_entry(self, entry):
        try:
            entry()
        except Exception, exc:
            typ, val, tb = einfo = sys.exc_info()
            if not self.schedule.handle_error(einfo):
                warnings.warn(TimedFunctionFailed(repr(exc))),
                traceback.print_exception(typ, val, tb) 
Example 33
Project: MSI-Keyboard-Lights   Author: CosmicSubspace   File: ScreenMirror.py    MIT License 5 votes vote down vote up
def show_exception_and_exit(exc_type, exc_value, tb):
        if not str(exc_value)=='name \'exit\' is not defined':
            print("\n\n---ERROR---\n")
            traceback.print_exception(exc_type, exc_value, tb)
            input("\nPress any key to exit.")
        sys.exit(-1) 
Example 34
Project: MSI-Keyboard-Lights   Author: CosmicSubspace   File: AudioAmplitude.py    MIT License 5 votes vote down vote up
def show_exception_and_exit(exc_type, exc_value, tb):
        if not str(exc_value)=='name \'exit\' is not defined':
            print("\n\n---ERROR---\n")
            traceback.print_exception(exc_type, exc_value, tb)
            input("\nPress any key to exit.")
        sys.exit(-1) 
Example 35
Project: MSI-Keyboard-Lights   Author: CosmicSubspace   File: MsiKeyboardLib.py    MIT License 5 votes vote down vote up
def show_exception_and_exit(exc_type, exc_value, tb):
        if not str(exc_value)=='name \'exit\' is not defined':
            print("\n\n---ERROR---\n")
            traceback.print_exception(exc_type, exc_value, tb)
            input("\nPress any key to exit.")
        sys.exit(-1) 
Example 36
Project: Repobot   Author: Desgard   File: crashhandler.py    MIT License 5 votes vote down vote up
def crash_handler_lite(etype, evalue, tb):
    """a light excepthook, adding a small message to the usual traceback"""
    traceback.print_exception(etype, evalue, tb)
    
    from IPython.core.interactiveshell import InteractiveShell
    if InteractiveShell.initialized():
        # we are in a Shell environment, give %magic example
        config = "%config "
    else:
        # we are not in a shell, show generic config
        config = "c."
    print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr) 
Example 37
Project: razzy-spinner   Author: rafasashi   File: doctest_driver.py    GNU General Public License v3.0 5 votes vote down vote up
def _exception_traceback(exc_info):
    excout = StringIO()
    exc_type, exc_val, exc_tb = exc_info
    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
    return excout.getvalue() 
Example 38
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydevd.py    MIT License 5 votes vote down vote up
def handle_breakpoint_condition(self, info, pybreakpoint, new_frame):
        condition = pybreakpoint.condition
        try:
            if pybreakpoint.handle_hit_condition(new_frame):
                return True

            if not condition:
                return False

            return eval(condition, new_frame.f_globals, new_frame.f_locals)
        except Exception as e:
            if IS_PY2:
                # Must be bytes on py2.
                if isinstance(condition, unicode):  # noqa
                    condition = condition.encode('utf-8')

            if not isinstance(e, self.skip_print_breakpoint_exception):
                sys.stderr.write('Error while evaluating expression: %s\n' % (condition,))

                etype, value, tb = sys.exc_info()
                traceback.print_exception(etype, value, tb.tb_next)

            if not isinstance(e, self.skip_suspend_on_breakpoint_exception):
                try:
                    # add exception_type and stacktrace into thread additional info
                    etype, value, tb = sys.exc_info()
                    error = ''.join(traceback.format_exception_only(etype, value))
                    stack = traceback.extract_stack(f=tb.tb_frame.f_back)

                    # On self.set_suspend(thread, CMD_SET_BREAK) this info will be
                    # sent to the client.
                    info.conditional_breakpoint_exception = \
                        ('Condition:\n' + condition + '\n\nError:\n' + error, stack)
                except:
                    pydev_log.exception()
                return True

            return False

        finally:
            etype, value, tb = None, None, None 
Example 39
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydev_runfiles_unittest.py    MIT License 5 votes vote down vote up
def _reportErrors(self, errors, failures, captured_output, test_name, diff_time=''):
        error_contents = []
        for test, s in errors+failures:
            if type(s) == type((1,)): #If it's a tuple (for jython 2.1)
                sio = StringIO()
                traceback.print_exception(s[0], s[1], s[2], file=sio)
                s = sio.getvalue()
            error_contents.append(s)

        sep = '\n'+self.separator1
        error_contents = sep.join(error_contents)

        if errors and not failures:
            try:
                pydev_runfiles_xml_rpc.notifyTest(
                    'error', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time)
            except:
                file_start = error_contents.find('File "')
                file_end = error_contents.find('", ', file_start)
                if file_start != -1 and file_end != -1:
                    file = error_contents[file_start+6:file_end]
                else:
                    file = '<unable to get file>'
                pydev_runfiles_xml_rpc.notifyTest(
                    'error', captured_output, error_contents, file, test_name, diff_time)

        elif failures and not errors:
            pydev_runfiles_xml_rpc.notifyTest(
                'fail', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time)

        else: #Ok, we got both, errors and failures. Let's mark it as an error in the end.
            pydev_runfiles_xml_rpc.notifyTest(
                'error', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time) 
Example 40
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydevd_tracing.py    MIT License 5 votes vote down vote up
def get_exception_traceback_str():
    exc_info = sys.exc_info()
    s = StringIO.StringIO()
    traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], file=s)
    return s.getvalue() 
Example 41
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: _pydev_log.py    MIT License 5 votes vote down vote up
def add_exception(self):
        s = StringIO.StringIO()
        exc_info = sys.exc_info()
        traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], limit=None, file=s)
        self._contents.append(s.getvalue()) 
Example 42
Project: inmanta   Author: inmanta   File: app.py    Apache License 2.0 5 votes vote down vote up
def start_server(options: argparse.Namespace) -> None:
    if options.config_file and not os.path.exists(options.config_file):
        LOGGER.warning("Config file %s doesn't exist", options.config_file)

    if options.config_dir and not os.path.isdir(options.config_dir):
        LOGGER.warning("Config directory %s doesn't exist", options.config_dir)

    ibl = InmantaBootloader()
    setup_signal_handlers(ibl.stop)

    ioloop = IOLoop.current()

    # handle startup exceptions
    def _handle_startup_done(fut: asyncio.Future) -> None:
        if fut.cancelled():
            safe_shutdown(ioloop, ibl.stop)
        else:
            exc = fut.exception()
            if exc is not None:
                LOGGER.exception("Server setup failed", exc_info=exc)
                traceback.print_exception(type(exc), exc, exc.__traceback__)
                safe_shutdown(ioloop, ibl.stop)
            else:
                LOGGER.info("Server startup complete")

    ensure_future(ibl.start()).add_done_callback(_handle_startup_done)

    ioloop.start()
    LOGGER.info("Server shutdown complete")
    if not ibl.started:
        exit(EXIT_START_FAILED) 
Example 43
Project: jwalk   Author: jwplayer   File: __main__.py    Apache License 2.0 5 votes vote down vote up
def debug_hook(type_, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        sys.__excepthook__(type_, value, tb)
    else:
        import traceback
        import pdb
        traceback.print_exception(type_, value, tb)
        print(u"\n")
        pdb.pm() 
Example 44
Project: chattR   Author: patrickstocklin   File: basecommand.py    GNU General Public License v2.0 5 votes vote down vote up
def format_exc(exc_info=None):
    if exc_info is None:
        exc_info = sys.exc_info()
    out = StringIO()
    traceback.print_exception(*exc_info, **dict(file=out))
    return out.getvalue() 
Example 45
Project: 3D-R2N2   Author: chrischoy   File: data_process.py    MIT License 5 votes vote down vote up
def print_error(func):
    '''Flush out error messages. Mainly used for debugging separate processes'''

    def func_wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            traceback.print_exception(*sys.exc_info())
            sys.stdout.flush()

    return func_wrapper 
Example 46
Project: TornadoWeb   Author: VxCoder   File: threadpool.py    Apache License 2.0 5 votes vote down vote up
def _handle_thread_exception(request, exc_info):
    """Default exception handler callback function.

    This just prints the exception info via ``traceback.print_exception``.

    """
    traceback.print_exception(*exc_info)


# utility functions 
Example 47
Project: TornadoWeb   Author: VxCoder   File: threadpool.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, callable_, args=None, kwds=None, requestID=None,
            callback=None, exc_callback=_handle_thread_exception):
        """Create a work request for a callable and attach callbacks.

        A work request consists of the a callable to be executed by a
        worker thread, a list of positional arguments, a dictionary
        of keyword arguments.

        A ``callback`` function can be specified, that is called when the
        results of the request are picked up from the result queue. It must
        accept two anonymous arguments, the ``WorkRequest`` object and the
        results of the callable, in that order. If you want to pass additional
        information to the callback, just stick it on the request object.

        You can also give custom callback for when an exception occurs with
        the ``exc_callback`` keyword parameter. It should also accept two
        anonymous arguments, the ``WorkRequest`` and a tuple with the exception
        details as returned by ``sys.exc_info()``. The default implementation
        of this callback just prints the exception info via
        ``traceback.print_exception``. If you want no exception handler
        callback, just pass in ``None``.

        ``requestID``, if given, must be hashable since it is used by
        ``ThreadPool`` object to store the results of that work request in a
        dictionary. It defaults to the return value of ``id(self)``.

        """
        if requestID is None:
            self.requestID = id(self)
        else:
            try:
                self.requestID = hash(requestID)
            except TypeError:
                raise TypeError("requestID must be hashable.")
        self.exception = False
        self.callback = callback
        self.exc_callback = exc_callback
        self.callable = callable_
        self.args = args or []
        self.kwds = kwds or {} 
Example 48
Project: pythonista-tools-installer   Author: ywangd   File: ptinstaller.py    MIT License 5 votes vote down vote up
def _install(self, btn):
        self.activity_indicator.start()
        install_path = PythonistaToolsInstaller.get_install_path()
        target_folder = PythonistaToolsInstaller.get_target_folder(btn.category_name,
                                                                   btn.tool_name)
        try:
            if self.gist_installer.get_gist_id(btn.tool_url):
                if not os.path.exists(target_folder):
                    os.makedirs(target_folder)
                self.gist_installer.install(btn.tool_url, target_folder)
            elif self.github_installer.get_github_user_repo(btn.tool_url):
                if not os.path.exists(target_folder):
                    os.makedirs(target_folder)
                self.github_installer.install(btn.tool_url, target_folder)
            else:  # any other url types, including iTunes
                webbrowser.open(btn.tool_url)
            btn.set_state_uninstall()
            console.hud_alert('%s installed at %s' % (btn.tool_name, install_path), 'success', 1.0)
        except Exception as e:
            # clean up the directory
            if os.path.exists(target_folder):
                shutil.rmtree(target_folder)
            btn.set_state_install()  # revert the state
            # Display some debug messages
            etype, evalue, tb = sys.exc_info()
            sys.stderr.write('%s\n' % repr(e))
            import traceback
            traceback.print_exception(etype, evalue, tb)
            console.hud_alert('Installation failed', 'error', 1.0)
        finally:
            self.activity_indicator.stop() 
Example 49
Project: link-prediction_with_deep-learning   Author: cambridgeltl   File: __main__.py    MIT License 5 votes vote down vote up
def debug(type_, value, tb):
  if hasattr(sys, 'ps1') or not sys.stderr.isatty():
    sys.__excepthook__(type_, value, tb)
  else:
    import traceback
    import pdb
    traceback.print_exception(type_, value, tb)
    print(u"\n")
    pdb.pm() 
Example 50
Project: link-prediction_with_deep-learning   Author: cambridgeltl   File: __main__.py    MIT License 5 votes vote down vote up
def debug(type_, value, tb):
  if hasattr(sys, 'ps1') or not sys.stderr.isatty():
    sys.__excepthook__(type_, value, tb)
  else:
    import traceback
    import pdb
    traceback.print_exception(type_, value, tb)
    print(u"\n")
    pdb.pm() 
Example 51
Project: Flask_Blog   Author: sugarguo   File: basecommand.py    GNU General Public License v3.0 5 votes vote down vote up
def format_exc(exc_info=None):
    if exc_info is None:
        exc_info = sys.exc_info()
    out = StringIO()
    traceback.print_exception(*exc_info, **dict(file=out))
    return out.getvalue() 
Example 52
Project: Flask_Blog   Author: sugarguo   File: doctest.py    GNU General Public License v3.0 5 votes vote down vote up
def _exception_traceback(exc_info):
    """
    Return a string containing a traceback message for the given
    exc_info tuple (as returned by sys.exc_info()).
    """
    # Get a traceback message.
    excout = StringIO()
    exc_type, exc_val, exc_tb = exc_info
    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
    return excout.getvalue()

# Override some StringIO methods. 
Example 53
Project: NiujiaoDebugger   Author: MrSrc   File: doctest.py    GNU General Public License v3.0 5 votes vote down vote up
def _exception_traceback(exc_info):
    """
    Return a string containing a traceback message for the given
    exc_info tuple (as returned by sys.exc_info()).
    """
    # Get a traceback message.
    excout = StringIO()
    exc_type, exc_val, exc_tb = exc_info
    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
    return excout.getvalue()

# Override some StringIO methods. 
Example 54
Project: NiujiaoDebugger   Author: MrSrc   File: test_traceback.py    GNU General Public License v3.0 5 votes vote down vote up
def test_print_traceback_at_exit(self):
        # Issue #22599: Ensure that it is possible to use the traceback module
        # to display an exception at Python exit
        code = textwrap.dedent("""
            import sys
            import traceback

            class PrintExceptionAtExit(object):
                def __init__(self):
                    try:
                        x = 1 / 0
                    except Exception:
                        self.exc_info = sys.exc_info()
                        # self.exc_info[1] (traceback) contains frames:
                        # explicitly clear the reference to self in the current
                        # frame to break a reference cycle
                        self = None

                def __del__(self):
                    traceback.print_exception(*self.exc_info)

            # Keep a reference in the module namespace to call the destructor
            # when the module is unloaded
            obj = PrintExceptionAtExit()
        """)
        rc, stdout, stderr = assert_python_ok('-c', code)
        expected = [b'Traceback (most recent call last):',
                    b'  File "<string>", line 8, in __init__',
                    b'ZeroDivisionError: division by zero']
        self.assertEqual(stderr.splitlines(), expected) 
Example 55
Project: NiujiaoDebugger   Author: MrSrc   File: test_traceback.py    GNU General Public License v3.0 5 votes vote down vote up
def get_report(self, e):
        e = self.get_exception(e)
        s = ''.join(
            traceback.format_exception(type(e), e, e.__traceback__))
        with captured_output("stderr") as sio:
            traceback.print_exception(type(e), e, e.__traceback__)
        self.assertEqual(sio.getvalue(), s)
        return s 
Example 56
Project: NiujiaoDebugger   Author: MrSrc   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def report_callback_exception(self, exc, val, tb):
        """Report callback exception on sys.stderr.

        Applications may want to override this internal function, and
        should when sys.stderr is None."""
        import traceback
        print("Exception in Tkinter callback", file=sys.stderr)
        sys.last_type = exc
        sys.last_value = val
        sys.last_traceback = tb
        traceback.print_exception(exc, val, tb) 
Example 57
Project: NiujiaoDebugger   Author: MrSrc   File: run.py    GNU General Public License v3.0 5 votes vote down vote up
def print_exception():
    import linecache
    linecache.checkcache()
    flush_stdout()
    efile = sys.stderr
    typ, val, tb = excinfo = sys.exc_info()
    sys.last_type, sys.last_value, sys.last_traceback = excinfo
    seen = set()

    def print_exc(typ, exc, tb):
        seen.add(id(exc))
        context = exc.__context__
        cause = exc.__cause__
        if cause is not None and id(cause) not in seen:
            print_exc(type(cause), cause, cause.__traceback__)
            print("\nThe above exception was the direct cause "
                  "of the following exception:\n", file=efile)
        elif (context is not None and
              not exc.__suppress_context__ and
              id(context) not in seen):
            print_exc(type(context), context, context.__traceback__)
            print("\nDuring handling of the above exception, "
                  "another exception occurred:\n", file=efile)
        if tb:
            tbe = traceback.extract_tb(tb)
            print('Traceback (most recent call last):', file=efile)
            exclude = ("run.py", "rpc.py", "threading.py", "queue.py",
                       "debugger_r.py", "bdb.py")
            cleanup_traceback(tbe, exclude)
            traceback.print_list(tbe, file=efile)
        lines = traceback.format_exception_only(typ, exc)
        for line in lines:
            print(line, end='', file=efile)

    print_exc(typ, val, tb) 
Example 58
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: backend_wx.py    MIT License 5 votes vote down vote up
def debug_on_error(type, value, tb):
    """Code due to Thomas Heller - published in Python Cookbook (O'Reilly)"""
    import pdb
    import traceback
    traceback.print_exception(type, value, tb)
    print()
    pdb.pm() 
Example 59
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: ToolsPage.py    MIT License 5 votes vote down vote up
def __init__(self, gcode):
		self.gcode  = gcode
		self.inches = False
		self.digits = 4
		self.active = StringVar()

		self.tools   = {}
		self.buttons = {}
		self.listbox = None

		# CNC should be first to load the inches
		for cls in [ Camera, Config, Font, Color, Controller, Cut,
			     Drill, EndMill, Events, Material, Pocket,
			     Profile, Shortcut, Stock, Tabs]:
			tool = cls(self)
			self.addTool(tool)

		# Find plugins in the plugins directory and load them
		for f in glob.glob("%s/plugins/*.py"%(Utils.prgpath)):
			name,ext = os.path.splitext(os.path.basename(f))
			try:
				exec("import %s"%(name))
				tool = eval("%s.Tool(self)"%(name))
				self.addTool(tool)
			except (ImportError, AttributeError):
				typ, val, tb = sys.exc_info()
				traceback.print_exception(typ, val, tb)

	# ---------------------------------------------------------------------- 
Example 60
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: bCNC.py    MIT License 5 votes vote down vote up
def monitorSerial(self):
		try:
			self._monitorSerial()
		except:
			typ, val, tb = sys.exc_info()
			traceback.print_exception(typ, val, tb)
		self.after(MONITOR_AFTER, self.monitorSerial)

	#----------------------------------------------------------------------- 
Example 61
Project: whatweb   Author: ourren   File: threadpool.py    GNU General Public License v2.0 5 votes vote down vote up
def _handle_thread_exception(request, exc_info):
    """Default exception handler callback function.

    This just prints the exception info via ``traceback.print_exception``.

    """
    traceback.print_exception(*exc_info)


# utility functions 
Example 62
Project: whatweb   Author: ourren   File: threadpool.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, callable_, args=None, kwds=None, requestID=None,
            callback=None, exc_callback=_handle_thread_exception):
        """Create a work request for a callable and attach callbacks.

        A work request consists of the a callable to be executed by a
        worker thread, a list of positional arguments, a dictionary
        of keyword arguments.

        A ``callback`` function can be specified, that is called when the
        results of the request are picked up from the result queue. It must
        accept two anonymous arguments, the ``WorkRequest`` object and the
        results of the callable, in that order. If you want to pass additional
        information to the callback, just stick it on the request object.

        You can also give custom callback for when an exception occurs with
        the ``exc_callback`` keyword parameter. It should also accept two
        anonymous arguments, the ``WorkRequest`` and a tuple with the exception
        details as returned by ``sys.exc_info()``. The default implementation
        of this callback just prints the exception info via
        ``traceback.print_exception``. If you want no exception handler
        callback, just pass in ``None``.

        ``requestID``, if given, must be hashable since it is used by
        ``ThreadPool`` object to store the results of that work request in a
        dictionary. It defaults to the return value of ``id(self)``.

        """
        if requestID is None:
            self.requestID = id(self)
        else:
            try:
                self.requestID = hash(requestID)
            except TypeError:
                raise TypeError("requestID must be hashable.")
        self.exception = False
        self.callback = callback
        self.exc_callback = exc_callback
        self.callable = callable_
        self.args = args or []
        self.kwds = kwds or {} 
Example 63
Project: discord.py   Author: Rapptz   File: player.py    MIT License 5 votes vote down vote up
def _call_after(self):
        error = self._current_error

        if self.after is not None:
            try:
                self.after(error)
            except Exception as exc:
                log.exception('Calling the after function failed.')
                exc.__context__ = error
                traceback.print_exception(type(exc), exc, exc.__traceback__)
        elif error:
            msg = 'Exception in voice thread {}'.format(self.name)
            log.exception(msg, exc_info=error)
            print(msg, file=sys.stderr)
            traceback.print_exception(type(error), error, error.__traceback__) 
Example 64
Project: Alexa-Ecovacs   Author: EtienneMD   File: cmdline.py    MIT License 5 votes vote down vote up
def main(argv=None):
    """The main entry point to coverage.py.

    This is installed as the script entry point.

    """
    if argv is None:
        argv = sys.argv[1:]
    try:
        status = CoverageScript().command_line(argv)
    except ExceptionDuringRun as err:
        # An exception was caught while running the product code.  The
        # sys.exc_info() return tuple is packed into an ExceptionDuringRun
        # exception.
        traceback.print_exception(*err.args)    # pylint: disable=no-value-for-parameter
        status = ERR
    except BaseCoverageException as err:
        # A controlled error inside coverage.py: print the message to the user.
        print(err)
        status = ERR
    except SystemExit as err:
        # The user called `sys.exit()`.  Exit with their argument, if any.
        if err.args:
            status = err.args[0]
        else:
            status = None
    return status 
Example 65
Project: neo4j-social-network   Author: bestvibes   File: basecommand.py    MIT License 5 votes vote down vote up
def format_exc(exc_info=None):
    if exc_info is None:
        exc_info = sys.exc_info()
    out = StringIO()
    traceback.print_exception(*exc_info, **dict(file=out))
    return out.getvalue() 
Example 66
Project: neo4j-social-network   Author: bestvibes   File: doctest.py    MIT License 5 votes vote down vote up
def _exception_traceback(exc_info):
    """
    Return a string containing a traceback message for the given
    exc_info tuple (as returned by sys.exc_info()).
    """
    # Get a traceback message.
    excout = StringIO()
    exc_type, exc_val, exc_tb = exc_info
    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
    return excout.getvalue()

# Override some StringIO methods. 
Example 67
Project: neo4j-social-network   Author: bestvibes   File: basecommand.py    MIT License 5 votes vote down vote up
def format_exc(exc_info=None):
    if exc_info is None:
        exc_info = sys.exc_info()
    out = StringIO()
    traceback.print_exception(*exc_info, **dict(file=out))
    return out.getvalue() 
Example 68
Project: centreon-discovery   Author: Centreon-Community   File: doctest.py    GNU General Public License v2.0 5 votes vote down vote up
def _exception_traceback(exc_info):
    """
    Return a string containing a traceback message for the given
    exc_info tuple (as returned by sys.exc_info()).
    """
    # Get a traceback message.
    excout = StringIO()
    exc_type, exc_val, exc_tb = exc_info
    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
    return excout.getvalue()

# Override some StringIO methods. 
Example 69
Project: tf-pose   Author: SrikanthVelpuri   File: exceptionHandling.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, *args):
        ## Start by extending recursion depth just a bit. 
        ## If the error we are catching is due to recursion, we don't want to generate another one here.
        recursionLimit = sys.getrecursionlimit()
        try:
            sys.setrecursionlimit(recursionLimit+100)
        
        
            ## call original exception handler first (prints exception)
            global original_excepthook, callbacks, clear_tracebacks
            try:
                print("===== %s =====" % str(time.strftime("%Y.%m.%d %H:%m:%S", time.localtime(time.time()))))
            except Exception:
                sys.stderr.write("Warning: stdout is broken! Falling back to stderr.\n")
                sys.stdout = sys.stderr

            ret = original_excepthook(*args)
                
            for cb in callbacks:
                try:
                    cb(*args)
                except Exception:
                    print("   --------------------------------------------------------------")
                    print("      Error occurred during exception callback %s" % str(cb))
                    print("   --------------------------------------------------------------")
                    traceback.print_exception(*sys.exc_info())
                
            
            ## Clear long-term storage of last traceback to prevent memory-hogging.
            ## (If an exception occurs while a lot of data is present on the stack, 
            ## such as when loading large files, the data would ordinarily be kept
            ## until the next exception occurs. We would rather release this memory 
            ## as soon as possible.)
            if clear_tracebacks is True:
                sys.last_traceback = None
        
        finally:
            sys.setrecursionlimit(recursionLimit) 
Example 70
Project: chowk   Author: fortyplustwo   File: tasks.py    Apache License 2.0 4 votes vote down vote up
def send_to_kannel( msg = {}, preferred_kannel_server = None):
    '''sends a given messages to the _RIGHT_ kannel server'''
    server = None
    if preferred_kannel_server is not None:
        try:
            server = KANNEL_SERVERS[preferred_kannel_server.lower()] #locate using ip
        except KeyError as ke:
            server = KANNEL_SERVERS['DEFAULT_KANNEL_SERVER']
    else: #no preferred server was given, select the proper one based on the recipient number
    
        for s,s_info in KANNEL_SERVERS.items():
            prefixes = s_info['series']
            logger.debug("Server %s supports all numbers with the prefixes %s", s, prefixes)
            for p in prefixes:
                recipient = msg['to'].strip('+')
                logger.debug("Trying to match %s with prefix %s ", recipient, p)
                if recipient.startswith(p): #this is our number series
                    server = s_info 
                    logger.debug("Selected server %s with prefix (%s) matching with recipient number %s", server, prefixes,recipient)
                    break;

            if server is not None: #we have found our server!
                break;

    if server is None:
        logger.error("Could not select any server for forwarding message! Check logs.")
        return (False, 500, '')

    try:
        #compose the complete Request with URL and data for sending sms
        session = Session()

        request = session.prepare_request(compose_request_for_kannel(msg, server))
        logger.debug("Calling %s with data %s", request.url, request.body)
        response = session.send(request)

        print response.status_code
        print response.text
        logger.debug("Received response code %s with text %s", response.status_code, response.text)
        logger.debug("Result is %s %s ", response.status_code, response.text)
        exc_info = sys.exc_info()

        return (True, response.status_code, response.text)
    except requests.ConnectionError as ce:
        exc_info = sys.exc_info()
        logger.critical("Problem while connecting to the server!")
        logger.exception(ce)

        return (False, response.status_code, response.text)
    finally:
        exc_info = sys.exc_info()
        traceback.print_exception(*exc_info)
        del exc_info 
Example 71
Project: chowk   Author: fortyplustwo   File: chowk.py    Apache License 2.0 4 votes vote down vote up
def sendsms():
    '''Handles and processes all messages coming from RapidPro server and going towards Kannel servers'''
    try:
        #TODO: Validate data and sanitize it a bit (?? sanitizing necessary ??)

        #Collect data in the msg
        msg = {}
        msg['to'] = request.form['to']
        msg['channel'] = request.form['channel']
        msg['from'] = request.form['from']
        msg['text'] = request.form['text']
        msg['id'] = request.form['id']

        app.logger.debug("We got request form data in the body as", request.form)
    
        #construct and send it forward
        r = send_to_kannel.apply_async(kwargs = {'msg': msg}, serializer = 'json')
        r.wait()
        status, status_code, status_msg = r.result
        exc_info = sys.exc_info()

        #We now try to find out the cause for failures, if any.
        #TODO: Handle this using and raising exceptions in send_to_kannel instead of anything else.

        if status_code == 403: #AuthenticationError with the Kannel
            app.logger.critical("Internal authentication error when trying to send the message to %s! Check config!", msg['to'])
            app.logger.critical("MSG Details are %s", msg)
            abort(500)
        elif status != False or status_code != 200:
            return "Bad luck! Couldn't deliver your message. Try again later in 30 minutes."
            abort(500)
        else:
            #report back to the RapidPro server about the success of delivery of this message
            app.logger.debug("Message %s succesfully forwarded to Kannel server", msg)
            report_status_to_rapidpro.apply_async(kwargs = {'status': 'SENT', 'msg': msg}, serializer = 'json')
            #we return in the format (response, status, headers) so that RapidPro knows that everything is HTTP 200 :)
            return ('',200,[])
    except KeyError as ke:
        exc_info = sys.exc_info()
        print "KeyError", ke
        app.logger.exception(ke)
        raise ke
        return "Wrong request data. Get off my server you idiot and RTFM!"
    except Exception as e:
        exc_info = sys.exc_info()
        print "Exception ", e
        app.logger.exception(e)
        raise e
        return "Error occured while trying to process your request"
    finally:
        traceback.print_exception(*exc_info)
        del exc_info 
Example 72
Project: Life   Author: MyNameBeMrRandom   File: events.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def on_command_error(self, ctx, error):

        # If the command has a local error handler, return
        if hasattr(ctx.command, "on_error"):
            return

        # Get the original exception or if nothing is found, keep the original exception.
        error = getattr(error, "original", error)

        # Check for errors.
        message = ""
        if isinstance(error, commands.CommandNotFound):
            return
        if isinstance(error, commands.MissingRequiredArgument):
            message = f"You missed the `{error.param}` parameter. You can use `{ctx.prefix}help {ctx.command}` for more information on what parameters to pass."
        if isinstance(error, commands.TooManyArguments):
            message = f"You passed too many arguments to the command `{ctx.command}`. You can use `{ctx.prefix}help {ctx.command}` for more information on what arguments to pass."
        if isinstance(error, commands.BadArgument):
            message = f"You passed a bad arguement to the command `{ctx.command}`."
        if isinstance(error, commands.PrivateMessageOnly):
            message = f"The command `{ctx.command}` can only be used in DM's."
        if isinstance(error, commands.NoPrivateMessage):
            try:
                message = f"The command `{ctx.command}` can not be used in DM's."
            except discord.Forbidden:
                return
        if isinstance(error, commands.NotOwner):
            message = f"The command `{ctx.command}` is owner only."
        if isinstance(error, commands.MissingPermissions):
            missing_perms = ">>> \n"
            for perm in error.missing_perms:
                missing_perms += f"{perm}\n"
            message = f"You don't have the following permissions required to run the command `{ctx.command}`.\n{missing_perms}"
        if isinstance(error, commands.BotMissingPermissions):
            missing_perms = ">>> \n"
            for perm in error.missing_perms:
                missing_perms += f"{perm}\n"
            message = f"I am missing the following permissions to run the command `{ctx.command}`.\n{missing_perms}"
        if isinstance(error, commands.DisabledCommand):
            message = f"The command `{ctx.command}` is currently disabled."
        if isinstance(error, commands.CommandOnCooldown):
            if error.cooldown.type == commands.BucketType.user:
                message = f"The command `{ctx.command}` is on cooldown for you, retry in `{utils.format_time(error.retry_after)}`."
            if error.cooldown.type == commands.BucketType.default:
                message = f"The command `{ctx.command}` is on cooldown for the whole bot, retry in `{utils.format_time(error.retry_after)}`."
            if error.cooldown.type == commands.BucketType.guild:
                message = f"The command `{ctx.command}` is on cooldown for this guild, retry in `{utils.format_time(error.retry_after)}`."
        if isinstance(error, commands.CheckFailure):
            message = f"{error}"
        if isinstance(error, granitepy.NodesUnavailable):
            message = "There are no nodes available."

        # If an error was caught, send it.
        if message:
            return await ctx.send(message)
        # Otherwise, print the original error as a traceback.
        print(f"Ignoring exception in command {ctx.command}:")
        traceback.print_exception(type(error), error, error.__traceback__) 
Example 73
Project: pi_to_potter   Author: mamacker   File: magicwand.py    MIT License 4 votes vote down vote up
def FindWand():
    global old_frame,old_gray,p0,mask, line_mask, run_request, audioProcess
    try:
        last = time.time()
        t = threading.currentThread()
        print "Find wand..."
        while getattr(t, "do_run", True):
            now = time.time()
            if run_request:
                old_gray, old_frame = ProcessImage()
                p0 = GetPoints(old_gray)
                if p0 is not None:
                    frameMissingPoints = 0;
                    mask = np.zeros_like(old_frame)
                    line_mask = np.zeros_like(old_gray)
                    run_request = False
                    if audioProcess is not None:
                        audioProcess.kill();
                    try:
                        audioProcess = subprocess.Popen(["/usr/bin/aplay", '/home/pi/pi_to_potter/twinkle.wav']);
                    except:
                        if audioProcess is not None:
                            audioProcess.kill();
                            audioProcess = None
                else:
                    if audioProcess is not None:
                        audioProcess.kill();
                        audioProcess = None
                '''
                else:
                    cv2.imwrite("nowand/char" + str(time.time()) + ".png", old_frame);
                '''
                last = time.time()

            time.sleep(.3)
    except cv2.error as e:
        None
        print "Err:"
        print e
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print "*** print_exception:"
        traceback.print_exception(exc_type, exc_value, exc_traceback,
                                  limit=2, file=sys.stdout) 
Example 74
Project: NiujiaoDebugger   Author: MrSrc   File: __init__.py    GNU General Public License v3.0 4 votes vote down vote up
def handleError(self, record):
        """
        Handle errors which occur during an emit() call.

        This method should be called from handlers when an exception is
        encountered during an emit() call. If raiseExceptions is false,
        exceptions get silently ignored. This is what is mostly wanted
        for a logging system - most users will not care about errors in
        the logging system, they are more interested in application errors.
        You could, however, replace this with a custom handler if you wish.
        The record which was being processed is passed in to this method.
        """
        if raiseExceptions and sys.stderr:  # see issue 13807
            t, v, tb = sys.exc_info()
            try:
                sys.stderr.write('--- Logging error ---\n')
                traceback.print_exception(t, v, tb, None, sys.stderr)
                sys.stderr.write('Call stack:\n')
                # Walk the stack frame up until we're out of logging,
                # so as to print the calling context.
                frame = tb.tb_frame
                while (frame and os.path.dirname(frame.f_code.co_filename) ==
                       __path__[0]):
                    frame = frame.f_back
                if frame:
                    traceback.print_stack(frame, file=sys.stderr)
                else:
                    # couldn't find the right stack frame, for some reason
                    sys.stderr.write('Logged from file %s, line %s\n' % (
                                     record.filename, record.lineno))
                # Issue 18671: output logging message and arguments
                try:
                    sys.stderr.write('Message: %r\n'
                                     'Arguments: %s\n' % (record.msg,
                                                          record.args))
                except Exception:
                    sys.stderr.write('Unable to print the message and arguments'
                                     ' - possible formatting error.\nUse the'
                                     ' traceback above to help find the error.\n'
                                    )
            except OSError: #pragma: no cover
                pass    # see issue 5971
            finally:
                del t, v, tb 
Example 75
Project: git-aggregator   Author: acsone   File: main.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def run(args):
    """Load YAML and JSON configs and run the command specified
    in args.command"""

    repos = load_config(args.config, args.expand_env, args.force)

    jobs = max(args.jobs, 1)
    threads = []
    sem = threading.Semaphore(jobs)
    err_queue = Queue()

    for repo_dict in repos:
        if not err_queue.empty():
            break

        sem.acquire()
        r = Repo(**repo_dict)
        tname = os.path.basename(repo_dict['cwd'])

        if jobs > 1:
            t = threading.Thread(
                target=aggregate_repo, args=(r, args, sem, err_queue))
            t.daemon = True
            t.name = tname
            threads.append(t)
            t.start()
        else:
            with ThreadNameKeeper():
                threading.current_thread().name = tname
                aggregate_repo(r, args, sem, err_queue)

    for t in threads:
        t.join()

    if not err_queue.empty():
        while True:
            try:
                exc_type, exc_obj, exc_trace = err_queue.get_nowait()
            except EmptyQueue:
                break
            traceback.print_exception(exc_type, exc_obj, exc_trace)
        sys.exit(1) 
Example 76
Project: TAF   Author: couchbaselabs   File: cursor_drop_test.py    Apache License 2.0 4 votes vote down vote up
def call(self):
        self.thread_used = threading.currentThread().getName()
        self.started = time.time()
        try:
            temp=0
            docs=[]
            for i in xrange(self.num_items):
                start_message_id = global_vars.message_id
                if self.op_type == "create":
                    for j in xrange(random.randint(1,10)):
                        var = str(json.dumps(self.generate_GleambookMessages(i+self.start_from , global_vars.message_id)))
                        user = JsonTranscoder().stringToJsonObject(var);
#                         print i+self.start_from,global_vars.message_id
                        doc = JsonDocument.create(str(global_vars.message_id), user);
                        docs.append(doc)
                        temp+=1
                        if temp == self.batch_size:
                            try:
                                doc_op().bulkSet(self.msg_bucket, docs)
                            except:
                                print "Sleeping for 20 secs"
                                time.sleep(20)
                                try:
                                    doc_op().bulkUpsert(self.msg_bucket, docs)
                                except:
                                    print "skipping %s documents upload"%len(docs)
                                    pass
                            temp = 0
                            docs=[]
                        global_vars.message_id += 1
                    end_message_id = global_vars.message_id
                elif self.op_type == "update":
                    var = str(json.dumps(self.generate_GleambookMessages(i+self.start_from , i+start_message_id)))
                    user = JsonTranscoder().stringToJsonObject(var);
                    doc = JsonDocument.create(str(i+start_message_id), user);
                    docs.append(doc)
                    if temp == self.batch_size:
                        try:
                            doc_op().bulkUpsert(self.msg_bucket, docs)
                        except:
                            print "Sleeping for 20 secs"
                            time.sleep(20)
                            try:
                                doc_op().bulkUpsert(self.msg_bucket, docs)
                            except:
                                print "skipping %s documents upload"%len(docs)
                                pass
                        temp = 0
                        docs=[]           
                elif self.op_type == "delete":
                    try:
                        response = self.msg_bucket.remove(str(i+start_message_id));
                    except:
                        pass      
                self.loaded += 1
        except Exception, ex:
            import traceback
            traceback.print_exc()
            exc_info = sys.exc_info()
            traceback.print_exception(*exc_info)
            self.exception = ex 
Example 77
Project: TAF   Author: couchbaselabs   File: cursor_drop_test.py    Apache License 2.0 4 votes vote down vote up
def call(self):
        self.thread_used = threading.currentThread().getName()
        self.started = time.time()
        try:
            docs=[]
            temp=0
            for i in xrange(self.num_items):
                if self.op_type == "create":
                    var = str(json.dumps(self.generate_GleambookUser(i+self.start_from)))
                    user = JsonTranscoder().stringToJsonObject(var);
                    doc = JsonDocument.create(str(i+self.start_from), user);
                    docs.append(doc)
                    temp += 1
                    if temp == self.batch_size:
                        try:
                            doc_op().bulkSet(self.bucket, docs)
                        except:
                            print "Exception from Java SDK - create"
                            time.sleep(20)
                            try:
                                doc_op().bulkUpsert(self.bucket, docs)
                            except:
                                print "skipping %s documents upload"%len(docs)
                                pass
                        temp = 0
                        docs=[]
#                     response = self.bucket.insert(doc);
                elif self.op_type == "update":
                    var = str(json.dumps(self.generate_GleambookUser(i+self.start_from)))
                    user = JsonTranscoder().stringToJsonObject(var);
                    doc = JsonDocument.create(str(i+self.start_from), user);
                    docs.append(doc)
                    temp += 1
                    if temp == self.batch_size:
                        try:
                            doc_op().bulkUpsert(self.bucket, docs)
                        except:
                            print "Exception from Java SDK - create"
                            time.sleep(20)
                            try:
                                doc_op().bulkUpsert(self.bucket, docs)
                            except:
                                print "skipping %s documents upload"%len(docs)
                                pass
                        temp = 0
                        docs=[]
                    
                elif self.op_type == "delete":
                    try:
                        response = self.bucket.remove(str(i+self.start_from));
                    except:
                        print "Exception from Java SDK - remove"
                self.loaded += 1
        except Exception, ex:
            import traceback
            traceback.print_exc()
            exc_info = sys.exc_info()
            traceback.print_exception(*exc_info)
            self.exception = ex 
Example 78
Project: TAF   Author: couchbaselabs   File: kv_volume_functional_basic_test.py    Apache License 2.0 4 votes vote down vote up
def call(self):
        self.thread_used = threading.currentThread().getName()
        self.started = time.time()
        try:
            docs=[]
            temp=0
            for i in xrange(self.num_items):
                if self.op_type == "create":
                    var = str(json.dumps(self.generate_GleambookUser(i+self.start_from)))
                    user = JsonTranscoder().stringToJsonObject(var);
                    doc = JsonDocument.create(str(i+self.start_from), user);
                    docs.append(doc)
                    temp += 1
                    if temp == self.batch_size:
                        try:
                            doc_op().bulkSet(self.bucket, docs)
                        except:
                            print "Exception from Java SDK - create"
                            time.sleep(20)
                            try:
                                doc_op().bulkUpsert(self.bucket, docs)
                            except:
                                print "skipping %s documents upload"%len(docs)
                                pass
                        temp = 0
                        docs=[]
#                     response = self.bucket.insert(doc);
                elif self.op_type == "update":
                    var = str(json.dumps(self.generate_GleambookUser(i+self.start_from)))
                    user = JsonTranscoder().stringToJsonObject(var);
                    doc = JsonDocument.create(str(i+self.start_from), user);
                    docs.append(doc)
                    temp += 1
                    if temp == self.batch_size:
                        try:
                            doc_op().bulkUpsert(self.bucket, docs)
                        except:
                            print "Exception from Java SDK - create"
                            time.sleep(20)
                            try:
                                doc_op().bulkUpsert(self.bucket, docs)
                            except:
                                print "skipping %s documents upload"%len(docs)
                                pass
                        temp = 0
                        docs=[]
                    
                elif self.op_type == "delete":
                    try:
                        response = self.bucket.remove(str(i+self.start_from));
                    except:
                        print "Exception from Java SDK - remove"
                self.loaded += 1
        except Exception, ex:
            import traceback
            traceback.print_exc()
            exc_info = sys.exc_info()
            traceback.print_exception(*exc_info)
            self.exception = ex 
Example 79
Project: TAF   Author: couchbaselabs   File: kv_volume_full_test.py    Apache License 2.0 4 votes vote down vote up
def call(self):
        self.thread_used = threading.currentThread().getName()
        self.started = time.time()
        try:
            temp=0
            docs=[]
            keys=[]
            for i in xrange(self.num_items):
                if self.op_type == "create":
#                     for j in xrange(3):
                    var = str(json.dumps(self.generate_GleambookMessages(i+self.start_from , self.start_from)))
                    user = JsonTranscoder().stringToJsonObject(var);
                    doc = JsonDocument.create(str(i+self.start_from), user);
                    docs.append(doc)
                    temp+=1
                    if temp == self.batch_size:
                        try:
                            doc_op().bulkSet(self.msg_bucket, docs)
                        except:
                            print "Sleeping for 20 secs"
                            time.sleep(20)
                            try:
                                doc_op().bulkUpsert(self.msg_bucket, docs)
                            except:
                                print "GleambookMessages_Docloader:skipping %s documents create"%len(docs)
                                pass
                        temp = 0
                        docs=[]   
#                         global_vars.message_id += 1
#                     end_message_id = global_vars.message_id
                elif self.op_type == "update":
                    var = str(json.dumps(self.generate_GleambookMessages(i+self.start_from , i+self.start_from)))
                    user = JsonTranscoder().stringToJsonObject(var);
                    doc = JsonDocument.create(str(i+self.start_from), user);
                    docs.append(doc)
                    if temp == self.batch_size:
                        try:
                            doc_op().bulkUpsert(self.msg_bucket, docs)
                        except:
                            print "Sleeping for 20 secs"
                            time.sleep(20)
                            try:
                                doc_op().bulkUpsert(self.msg_bucket, docs)
                            except:
                                print "GleambookMessages_Docloader:skipping %s documents upload"%len(docs)
                                pass
                        temp = 0
                        docs=[]           
                elif self.op_type == "delete":
                    try:
                        response = self.msg_bucket.remove(str(i+self.start_from));
                    except:
                        pass  
                self.loaded += 1
        except Exception, ex:
            import traceback
            traceback.print_exc()
            exc_info = sys.exc_info()
            traceback.print_exception(*exc_info)
            self.exception = ex 
Example 80
Project: TAF   Author: couchbaselabs   File: kv_volume_full_test.py    Apache License 2.0 4 votes vote down vote up
def call(self):
        self.thread_used = threading.currentThread().getName()
        self.started = time.time()
        try:
            docs=[]
            keys=[]
            temp=0
            for i in xrange(self.num_items):
                if self.op_type == "create":
                    var = str(json.dumps(self.generate_GleambookUser(i+self.start_from)))
                    user = JsonTranscoder().stringToJsonObject(var);
                    doc = JsonDocument.create(str(i+self.start_from), user);
                    docs.append(doc)
                    temp += 1
                    if temp == self.batch_size:
                        try:
                            doc_op().bulkSet(self.bucket, docs)
                        except:
                            print "Exception from Java SDK - create"
                            time.sleep(20)
                            try:
                                doc_op().bulkUpsert(self.bucket, docs)
                            except:
                                print "GleambookUser_Docloader: skipping %s documents create"%len(docs)
                                pass
                        temp = 0
                        docs=[]
#                     response = self.bucket.insert(doc);
                elif self.op_type == "update":
                    var = str(json.dumps(self.generate_GleambookUser(i+self.start_from)))
                    user = JsonTranscoder().stringToJsonObject(var);
                    doc = JsonDocument.create(str(i+self.start_from), user);
                    docs.append(doc)
                    temp += 1
                    if temp == self.batch_size:
                        try:
                            doc_op().bulkUpsert(self.bucket, docs)
                        except:
                            print "Exception from Java SDK - create"
                            time.sleep(20)
                            try:
                                doc_op().bulkUpsert(self.bucket, docs)
                            except:
                                print "GleambookUser_Docloader: skipping %s documents upload"%len(docs)
                                pass
                        temp = 0
                        docs=[]
                elif self.op_type == "delete":
                    try:
                        response = self.bucket.remove(str(i+self.start_from));
                    except:
                        print "Exception from Java SDK - remove"                    
                self.loaded += 1
        except Exception, ex:
            import traceback
            traceback.print_exc()
            exc_info = sys.exc_info()
            traceback.print_exception(*exc_info)
            self.exception = ex