def mainloop(self,sys_exit=0,banner=None):

        self._banner = banner
        
        if self.gtk.pygtk_version >= (2,4,0):
            import gobject
            gobject.idle_add(self.on_timer)
        else:
            self.gtk.idle_add(self.on_timer)

        if sys.platform != 'win32':
            try:
                if self.gtk.gtk_version[0] >= 2:
                    self.gtk.gdk.threads_init()
            except AttributeError:
                pass
            except RuntimeError:
                error('Your pyGTK likely has not been compiled with '
                      'threading support.\n'
                      'The exception printout is below.\n'
                      'You can either rebuild pyGTK with threads, or '
                      'try using \n'
                      'matplotlib with a different backend (like Tk or WX).\n'
                      'Note that matplotlib will most likely not work in its '
                      'current state!')
                self.IP.InteractiveTB()

        self.start()
        self.gtk.gdk.threads_enter()
        self.gtk_mainloop()
        self.gtk.gdk.threads_leave()
        self.join()
コード例 #2
0
ファイル: Shell.py プロジェクト: minrk/ipython-svn-archive
def _matplotlib_shell_class():
    """Factory function to handle shell class selection for matplotlib.

    The proper shell class to use depends on the matplotlib backend, since
    each backend requires a different threading strategy."""

    try:
        import matplotlib
    except ImportError:
        error('matplotlib could NOT be imported!  Starting normal IPython.')
        sh_class = IPShell
    else:
        backend = matplotlib.rcParams['backend']
        if backend.startswith('GTK'):
            sh_class = IPShellMatplotlibGTK
        elif backend.startswith('WX'):
            sh_class = IPShellMatplotlibWX
        elif backend.startswith('Qt4'):
            sh_class = IPShellMatplotlibQt4
        elif backend.startswith('Qt'):
            sh_class = IPShellMatplotlibQt
        else:
            sh_class = IPShellMatplotlib
    #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
    return sh_class
コード例 #3
0
ファイル: ultraTB.py プロジェクト: FrankBian/kuma
def inspect_error():
    """Print a message about internal inspect errors.

    These are unfortunately quite common."""
    
    error('Internal Python error in the inspect module.\n'
          'Below is the traceback from this internal error.\n')
コード例 #4
0
ファイル: ultraTB.py プロジェクト: minrk/ipython-svn-archive
def inspect_error():
    """Print a message about internal inspect errors.

    These are unfortunately quite common."""

    error('Internal Python error in the inspect module.\n'
          'Below is the traceback from this internal error.\n')
コード例 #5
0
ファイル: ipapi.py プロジェクト: minrk/ipython-svn-archive
    def to_user_ns(self, vars):
        """Inject a group of variables into the IPython user namespace.

        Inputs:

         - vars: string with variable names separated by whitespace

        This utility routine is meant to ease interactive debugging work,
        where you want to easily propagate some internal variable in your code
        up to the interactive namespace for further exploration.

        When you run code via %run, globals in your script become visible at
        the interactive prompt, but this doesn't happen for locals inside your
        own functions and methods.  Yet when debugging, it is common to want
        to explore some internal variables further at the interactive propmt.

        Examples:

        To use this, you first must obtain a handle on the ipython object as
        indicated above, via:

        import IPython.ipapi
        ip = IPython.ipapi.get()

        Once this is done, inside a routine foo() where you want to expose
        variables x and y, you do the following:

        def foo():
            ...
            x = your_computation()
            y = something_else()
            
            # This pushes x and y to the interactive prompt immediately, even
            # if this routine crashes on the next line after:
            ip.to_user_ns('x y')
            ...
            # return           
        
        If you need to rename variables, just use ip.user_ns with dict
        and update:
        
        # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython 
        # user namespace
        ip.user_ns.update(dict(x=foo,y=bar))    
        """

        # print 'vars given:',vars # dbg
        # Get the caller's frame to evaluate the given names in
        cf = sys._getframe(1)

        user_ns = self.user_ns

        for name in vars.split():
            try:
                user_ns[name] = eval(name, cf.f_globals, cf.f_locals)
            except:
                error('could not get var. %s from %s' %
                      (name, cf.f_code.co_name))
コード例 #6
0
    def remove(self, num):
        """Remove a finished (completed or dead) job."""

        try:
            job = self.jobs_all[num]
        except KeyError:
            error('Job #%s not found' % num)
        else:
            stat_code = job.stat_code
            if stat_code == self._s_running:
                error('Job #%s is still running, it can not be removed.' % num)
                return
            elif stat_code == self._s_completed:
                self.jobs_comp.remove(job)
            elif stat_code == self._s_dead:
                self.jobs_dead.remove(job)
コード例 #7
0
ファイル: background_jobs.py プロジェクト: beiske/play
    def remove(self,num):
        """Remove a finished (completed or dead) job."""

        try:
            job = self.jobs_all[num]
        except KeyError:
            error('Job #%s not found' % num)
        else:
            stat_code = job.stat_code
            if stat_code == self._s_running:
                error('Job #%s is still running, it can not be removed.' % num)
                return
            elif stat_code == self._s_completed:
                self.jobs_comp.remove(job)
            elif stat_code == self._s_dead:
                self.jobs_dead.remove(job)
コード例 #8
0
ファイル: Shell.py プロジェクト: minrk/ipython-svn-archive
    def __init__(self,
                 argv=None,
                 user_ns=None,
                 user_global_ns=None,
                 debug=1,
                 shell_class=MTInteractiveShell):

        self.IP = make_IPython(argv,
                               user_ns=user_ns,
                               user_global_ns=user_global_ns,
                               debug=debug,
                               shell_class=shell_class,
                               on_kill=[self.wxexit])

        wantedwxversion = self.IP.rc.wxversion
        if wantedwxversion != "0":
            try:
                import wxversion
            except ImportError:
                error(
                    'The wxversion module is needed for WX version selection')
            else:
                try:
                    wxversion.select(wantedwxversion)
                except:
                    self.IP.InteractiveTB()
                    error('Requested wxPython version %s could not be loaded' %
                          wantedwxversion)

        import wxPython.wx as wx

        threading.Thread.__init__(self)
        self.wx = wx
        self.wx_mainloop = hijack_wx()

        # Allows us to use both Tk and GTK.
        self.tk = get_tk()

        # HACK: slot for banner in self; it will be passed to the mainloop
        # method only and .run() needs it.  The actual value will be set by
        # .mainloop().
        self._banner = None

        self.app = None
コード例 #9
0
ファイル: Shell.py プロジェクト: CVL-dev/StructuralBiology
    def __init__(self,argv=None,user_ns=None,user_global_ns=None,
                 debug=1,shell_class=MTInteractiveShell):

        self.IP = make_IPython(argv,user_ns=user_ns,
                               user_global_ns=user_global_ns,
                               debug=debug,
                               shell_class=shell_class,
                               on_kill=[self.wxexit])

        wantedwxversion=self.IP.rc.wxversion
        if wantedwxversion!="0":
            try:
                import wxversion
            except ImportError:
                error('The wxversion module is needed for WX version selection')
            else:
                try:
                    wxversion.select(wantedwxversion)
                except:
                    self.IP.InteractiveTB()
                    error('Requested wxPython version %s could not be loaded' %
                                                               wantedwxversion)

        import wx

        threading.Thread.__init__(self)
        self.wx = wx
        self.wx_mainloop = hijack_wx()

        # Allows us to use both Tk and GTK.
        self.tk = get_tk()
        
        # HACK: slot for banner in self; it will be passed to the mainloop
        # method only and .run() needs it.  The actual value will be set by
        # .mainloop().
        self._banner = None 

        self.app = None
コード例 #10
0
ファイル: background_jobs.py プロジェクト: beiske/play
    def flush_finished(self):
        """Flush all jobs finished (completed and dead) from lists.

        Running jobs are never flushed.

        It first calls _status_new(), to update info. If any jobs have
        completed since the last _status_new() call, the flush operation
        aborts."""

        if self._status_new():
            error('New jobs completed since last '\
                  '_status_new(), aborting flush.')
            return

        # Remove the finished jobs from the master dict
        jobs_all = self.jobs_all
        for job in self.jobs_comp+self.jobs_dead:
            del(jobs_all[job.num])

        # Now flush these lists completely
        fl_comp = self._group_flush(self.jobs_comp,'Completed')
        fl_dead = self._group_flush(self.jobs_dead,'Dead')
        if not (fl_comp or fl_dead):
            print 'No jobs to flush.'
コード例 #11
0
    def flush_finished(self):
        """Flush all jobs finished (completed and dead) from lists.

        Running jobs are never flushed.

        It first calls _status_new(), to update info. If any jobs have
        completed since the last _status_new() call, the flush operation
        aborts."""

        if self._status_new():
            error('New jobs completed since last '\
                  '_status_new(), aborting flush.')
            return

        # Remove the finished jobs from the master dict
        jobs_all = self.jobs_all
        for job in self.jobs_comp + self.jobs_dead:
            del (jobs_all[job.num])

        # Now flush these lists completely
        fl_comp = self._group_flush(self.jobs_comp, 'Completed')
        fl_dead = self._group_flush(self.jobs_dead, 'Dead')
        if not (fl_comp or fl_dead):
            print 'No jobs to flush.'
コード例 #12
0
ファイル: ultraTB_10.py プロジェクト: kini/sagecell
    def text(self, etype, evalue, etb, context=5):
        """Return a nice text document describing the traceback."""

        try:
            etype = etype.__name__
        except AttributeError:
            pass
        Colors        = self.Colors   # just a shorthand + quicker name lookup
        ColorsNormal  = Colors.Normal  # used a lot
        col_scheme    = self.color_scheme_table.active_scheme_name
        indent        = ' '*INDENT_SIZE
        em_normal     = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
        undefined     = '%sundefined%s' % (Colors.em, ColorsNormal)
        exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)

        # some internal-use functions
        def text_repr(value):
            """Hopefully pretty robust repr equivalent."""
            try:
                return pydoc.text.repr(value)
            except KeyboardInterrupt:
                raise
            except:
                try:
                    return repr(value)
                except KeyboardInterrupt:
                    raise
                except:
                    try:
                        name = getattr(value, '__name__', None)
                        if name:
                            return text_repr(name)
                        klass = getattr(value, '__class__', None)
                        if klass:
                            return '%s instance' % text_repr(klass)
                    except KeyboardInterrupt:
                        raise
                    except:
                        return 'UNRECOVERABLE REPR FAILURE'
        def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
        def nullrepr(value, repr=text_repr): return ''

        try:
            etype = etype.__name__
        except AttributeError:
            pass

        if self.long_header:
            # Header with the exception type, python version, and date
            pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
            date = time.ctime(time.time())
            
            head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
                                           exc, ' '*(75-len(str(etype))-len(pyver)),
                                           pyver, string.rjust(date, 75) )
            head += "\nA problem occured executing Python code.  Here is the sequence of function"\
                    "\ncalls leading up to the error, with the most recent (innermost) call last."
        else:
            # Simplified header
            head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
                                     string.rjust('Traceback (most recent call last)',
                                                  75 - len(str(etype)) ) )
        frames = []
        linecache.checkcache()
        try:
            records = _fixed_getinnerframes(etb, context,self.tb_offset)
        except:
            inspect_error()
            traceback.print_exc(file=Term.cerr)
            info('\nUnfortunately, your original traceback can not be constructed.\n')
            return ''

        # build some color string templates outside these nested loops
        tpl_link       = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
        tpl_call       = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
                                              ColorsNormal)
        tpl_call_fail  = 'in %s%%s%s(***failed resolving arguments***)%s' % \
                         (Colors.vName, Colors.valEm, ColorsNormal)
        tpl_local_var  = '%s%%s%s' % (Colors.vName, ColorsNormal)
        tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
                                                 Colors.vName, ColorsNormal)
        tpl_name_val   = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
        tpl_line       = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
        tpl_line_em    = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
                                            ColorsNormal)

        abspath = os.path.abspath
        for frame, file, lnum, func, lines, index in records:
            #print '*** record:',file,lnum,func,lines,index  # dbg
            try:
                file = file and abspath(file) or '?'
            except OSError:
                pass
            link = tpl_link % file
            try:
                args, varargs, varkw, locals = inspect.getargvalues(frame)
            except:
                inspect_error()
                traceback.print_exc(file=Term.cerr)
                info("\nIPython's exception reporting continues...\n")
                
            if func == '?':
                call = ''
            else:
                # Decide whether to include variable details or not
                var_repr = self.include_vars and eqrepr or nullrepr
                try:
                    call = tpl_call % (func,inspect.formatargvalues(args,
                                                varargs, varkw,
                                                locals,formatvalue=var_repr))
                except KeyError:
                    inspect_error()
                    traceback.print_exc(file=Term.cerr)
                    info("\nIPython's exception reporting continues...\n")
                    call = tpl_call_fail % func

            names = []

            def tokeneater(token_type, token, start, end, line):
                """Stateful tokeneater which builds dotted names."""
                
                # build composite names
                if token == '.':
                    try:
                        names[-1] += '.'
                        # store state so the next token is added for x.y.z names
                        tokeneater.name_cont = True
                        return
                    except IndexError:
                        pass
                if token_type == tokenize.NAME and token not in keyword.kwlist:
                    if tokeneater.name_cont:
                        # Dotted names
                        names[-1] += token
                        tokeneater.name_cont = False
                    else:
                        names.append(token)
                elif token_type == tokenize.NEWLINE:
                    raise IndexError
            tokeneater.name_cont = False

            def linereader(file=file, lnum=[lnum], getline=linecache.getline):
                line = getline(file, lnum[0])
                lnum[0] += 1
                return line

            try:
                tokenize.tokenize(linereader, tokeneater)
            except IndexError:
                pass
            except tokenize.TokenError,msg:
                _m = ("An unexpected error occurred while tokenizing input\n"
                      "The following traceback may be corrupted or invalid\n"
                      "The error message is: %s\n" % msg)
                error(_m)
            
            # prune names list of duplicates, but keep the right order
            unique_names = uniq_stable(names)

            # Start loop over vars
            lvals = []
            if self.include_vars:
                for name_full in unique_names:
                    name_base = name_full.split('.',1)[0]
                    if name_base in frame.f_code.co_varnames:
                        if locals.has_key(name_base):
                            try:
                                value = repr(eval(name_full,locals))
                            except:
                                value = undefined
                        else:
                            value = undefined
                        name = tpl_local_var % name_full
                    else:
                        if frame.f_globals.has_key(name_base):
                            try:
                                value = repr(eval(name_full,frame.f_globals))
                            except:
                                value = undefined
                        else:
                            value = undefined
                        name = tpl_global_var % name_full
                    lvals.append(tpl_name_val % (name,value))
            if lvals:
                lvals = '%s%s' % (indent,em_normal.join(lvals))
            else:
                lvals = ''

            level = '%s %s\n' % (link,call)

            if index is None:
                frames.append(level)
            else:
                frames.append('%s%s' % (level,''.join(
                    _formatTracebackLines(lnum,index,lines,Colors,lvals,
                                          col_scheme))))
コード例 #13
0
ファイル: background_jobs.py プロジェクト: beiske/play
 def result(self,num):
     """result(N) -> return the result of job N."""
     try:
         return self.jobs_all[num].result
     except KeyError:
         error('Job #%s not found' % num)
コード例 #14
0
ファイル: ultraTB.py プロジェクト: minrk/ipython-svn-archive
    def text(self, etype, evalue, etb, context=5):
        """Return a nice text document describing the traceback."""

        # some locals
        Colors = self.Colors  # just a shorthand + quicker name lookup
        ColorsNormal = Colors.Normal  # used a lot
        indent_size = 8  # we need some space to put line numbers before
        indent = ' ' * indent_size
        numbers_width = indent_size - 1  # leave space between numbers & code
        text_repr = pydoc.text.repr
        exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
        em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
        undefined = '%sundefined%s' % (Colors.em, ColorsNormal)

        # some internal-use functions
        def eqrepr(value, repr=text_repr):
            return '=%s' % repr(value)

        def nullrepr(value, repr=text_repr):
            return ''

        # meat of the code begins
        if type(etype) is types.ClassType:
            etype = etype.__name__

        if self.long_header:
            # Header with the exception type, python version, and date
            pyver = 'Python ' + string.split(
                sys.version)[0] + ': ' + sys.executable
            date = time.ctime(time.time())

            head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-' * 75,
                                           ColorsNormal, exc, ' ' *
                                           (75 - len(str(etype)) - len(pyver)),
                                           pyver, string.rjust(date, 75))
            head += "\nA problem occured executing Python code.  Here is the sequence of function"\
                    "\ncalls leading up to the error, with the most recent (innermost) call last."
        else:
            # Simplified header
            head = '%s%s%s\n%s%s' % (
                Colors.topline, '-' * 75, ColorsNormal, exc,
                string.rjust('Traceback (most recent call last)',
                             75 - len(str(etype))))
        frames = []
        # Flush cache before calling inspect.  This helps alleviate some of the
        # problems with python 2.3's inspect.py.
        linecache.checkcache()
        # Drop topmost frames if requested
        try:
            records = inspect.getinnerframes(etb, context)[self.tb_offset:]
        except:

            # FIXME: I've been getting many crash reports from python 2.3
            # users, traceable to inspect.py.  If I can find a small test-case
            # to reproduce this, I should either write a better workaround or
            # file a bug report against inspect (if that's the real problem).
            # So far, I haven't been able to find an isolated example to
            # reproduce the problem.
            inspect_error()
            traceback.print_exc(file=Term.cerr)
            info(
                '\nUnfortunately, your original traceback can not be constructed.\n'
            )
            return ''

        # build some color string templates outside these nested loops
        tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
        tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
                                        ColorsNormal)
        tpl_call_fail  = 'in %s%%s%s(***failed resolving arguments***)%s' % \
                         (Colors.vName, Colors.valEm, ColorsNormal)
        tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
        tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
                                                 Colors.vName, ColorsNormal)
        tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
        tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
        tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
                                         ColorsNormal)

        # now, loop over all records printing context and info
        abspath = os.path.abspath
        for frame, file, lnum, func, lines, index in records:
            #print '*** record:',file,lnum,func,lines,index  # dbg
            try:
                file = file and abspath(file) or '?'
            except OSError:
                # if file is '<console>' or something not in the filesystem,
                # the abspath call will throw an OSError.  Just ignore it and
                # keep the original file string.
                pass
            link = tpl_link % file
            try:
                args, varargs, varkw, locals = inspect.getargvalues(frame)
            except:
                # This can happen due to a bug in python2.3.  We should be
                # able to remove this try/except when 2.4 becomes a
                # requirement.  Bug details at http://python.org/sf/1005466
                inspect_error()
                traceback.print_exc(file=Term.cerr)
                info("\nIPython's exception reporting continues...\n")

            if func == '?':
                call = ''
            else:
                # Decide whether to include variable details or not
                var_repr = self.include_vars and eqrepr or nullrepr
                try:
                    call = tpl_call % (
                        func,
                        inspect.formatargvalues(
                            args, varargs, varkw, locals,
                            formatvalue=var_repr))
                except KeyError:
                    # Very odd crash from inspect.formatargvalues().  The
                    # scenario under which it appeared was a call to
                    # view(array,scale) in NumTut.view.view(), where scale had
                    # been defined as a scalar (it should be a tuple). Somehow
                    # inspect messes up resolving the argument list of view()
                    # and barfs out. At some point I should dig into this one
                    # and file a bug report about it.
                    inspect_error()
                    traceback.print_exc(file=Term.cerr)
                    info("\nIPython's exception reporting continues...\n")
                    call = tpl_call_fail % func

            # Initialize a list of names on the current line, which the
            # tokenizer below will populate.
            names = []

            def tokeneater(token_type, token, start, end, line):
                """Stateful tokeneater which builds dotted names.

                The list of names it appends to (from the enclosing scope) can
                contain repeated composite names.  This is unavoidable, since
                there is no way to disambguate partial dotted structures until
                the full list is known.  The caller is responsible for pruning
                the final list of duplicates before using it."""

                # build composite names
                if token == '.':
                    try:
                        names[-1] += '.'
                        # store state so the next token is added for x.y.z names
                        tokeneater.name_cont = True
                        return
                    except IndexError:
                        pass
                if token_type == tokenize.NAME and token not in keyword.kwlist:
                    if tokeneater.name_cont:
                        # Dotted names
                        names[-1] += token
                        tokeneater.name_cont = False
                    else:
                        # Regular new names.  We append everything, the caller
                        # will be responsible for pruning the list later.  It's
                        # very tricky to try to prune as we go, b/c composite
                        # names can fool us.  The pruning at the end is easy
                        # to do (or the caller can print a list with repeated
                        # names if so desired.
                        names.append(token)
                elif token_type == tokenize.NEWLINE:
                    raise IndexError

            # we need to store a bit of state in the tokenizer to build
            # dotted names
            tokeneater.name_cont = False

            def linereader(file=file, lnum=[lnum], getline=linecache.getline):
                line = getline(file, lnum[0])
                lnum[0] += 1
                return line

            # Build the list of names on this line of code where the exception
            # occurred.
            try:
                # This builds the names list in-place by capturing it from the
                # enclosing scope.
                tokenize.tokenize(linereader, tokeneater)
            except IndexError:
                # signals exit of tokenizer
                pass
            except tokenize.TokenError, msg:
                _m = ("An unexpected error occurred while tokenizing input\n"
                      "The following traceback may be corrupted or invalid\n"
                      "The error message is: %s\n" % msg)
                error(_m)

            # prune names list of duplicates, but keep the right order
            unique_names = uniq_stable(names)

            # Start loop over vars
            lvals = []
            if self.include_vars:
                for name_full in unique_names:
                    name_base = name_full.split('.', 1)[0]
                    if name_base in frame.f_code.co_varnames:
                        if locals.has_key(name_base):
                            try:
                                value = repr(eval(name_full, locals))
                            except:
                                value = undefined
                        else:
                            value = undefined
                        name = tpl_local_var % name_full
                    else:
                        if frame.f_globals.has_key(name_base):
                            try:
                                value = repr(eval(name_full, frame.f_globals))
                            except:
                                value = undefined
                        else:
                            value = undefined
                        name = tpl_global_var % name_full
                    lvals.append(tpl_name_val % (name, value))
            if lvals:
                lvals = '%s%s' % (indent, em_normal.join(lvals))
            else:
                lvals = ''

            level = '%s %s\n' % (link, call)
            excerpt = []
            if index is not None:
                i = lnum - index
                for line in lines:
                    if i == lnum:
                        # This is the line with the error
                        pad = numbers_width - len(str(i))
                        if pad >= 3:
                            marker = '-' * (pad - 3) + '-> '
                        elif pad == 2:
                            marker = '> '
                        elif pad == 1:
                            marker = '>'
                        else:
                            marker = ''
                        num = '%s%s' % (marker, i)
                        line = tpl_line_em % (num, line)
                    else:
                        num = '%*s' % (numbers_width, i)
                        line = tpl_line % (num, line)

                    excerpt.append(line)
                    if self.include_vars and i == lnum:
                        excerpt.append('%s\n' % lvals)
                    i += 1
            frames.append('%s%s' % (level, ''.join(excerpt)))
コード例 #15
0
ファイル: background_jobs.py プロジェクト: beiske/play
 def traceback(self,num):
     try:
         self.jobs_all[num].traceback()
     except KeyError:
         error('Job #%s not found' % num)
def _select_shell(argv):
    """Select a shell from the given argv vector.

    This function implements the threading selection policy, allowing runtime
    control of the threading mode, both for general users and for matplotlib.

    Return:
      Shell class to be instantiated for runtime operation.
    """
    
    global USE_TK

    mpl_shell = {'gthread' : IPShellMatplotlibGTK,
                 'wthread' : IPShellMatplotlibWX,
                 'qthread' : IPShellMatplotlibQt,
                 'q4thread' : IPShellMatplotlibQt4,
                 'tkthread' : IPShellMatplotlib,  # Tk is built-in
                 }

    th_shell = {'gthread' : IPShellGTK,
                'wthread' : IPShellWX,
                'qthread' : IPShellQt,
                'q4thread' : IPShellQt4,
                'tkthread' : IPShell, # Tk is built-in
                }

    backends = {'gthread' : 'GTKAgg',
                'wthread' : 'WXAgg',
                'qthread' : 'QtAgg',
                'q4thread' :'Qt4Agg',
                'tkthread' :'TkAgg',
                }

    all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread',
                    'tkthread'])
    user_opts = set([s.replace('-','') for s in argv[:3]])
    special_opts = user_opts & all_opts            

    if 'tk' in special_opts:
        USE_TK = True
        special_opts.remove('tk')

    if 'pylab' in special_opts:

        try:
            import matplotlib
        except ImportError:
            error('matplotlib could NOT be imported!  Starting normal IPython.')
            return IPShell
        
        special_opts.remove('pylab')
        # If there's any option left, it means the user wants to force the
        # threading backend, else it's auto-selected from the rc file
        if special_opts:
            th_mode = special_opts.pop()
            matplotlib.rcParams['backend'] = backends[th_mode]
        else:
            backend = matplotlib.rcParams['backend']
            if backend.startswith('GTK'):
                th_mode = 'gthread'
            elif backend.startswith('WX'):
                th_mode = 'wthread'
            elif backend.startswith('Qt4'):
                th_mode = 'q4thread'
            elif backend.startswith('Qt'):
                th_mode = 'qthread'
            else:
                # Any other backend, use plain Tk
                th_mode = 'tkthread'
        return mpl_shell[th_mode]
    else:
        # No pylab requested, just plain threads
        try:
            th_mode = special_opts.pop()
        except KeyError:
            th_mode = 'tkthread'
        return th_shell[th_mode]
コード例 #17
0
ファイル: ultraTB.py プロジェクト: FrankBian/kuma
    def text(self, etype, evalue, etb, context=5):
        """Return a nice text document describing the traceback."""

        # some locals
        try:
            etype = etype.__name__
        except AttributeError:
            pass
        Colors        = self.Colors   # just a shorthand + quicker name lookup
        ColorsNormal  = Colors.Normal  # used a lot
        col_scheme    = self.color_scheme_table.active_scheme_name
        indent        = ' '*INDENT_SIZE
        em_normal     = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
        undefined     = '%sundefined%s' % (Colors.em, ColorsNormal)
        exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)

        # some internal-use functions
        def text_repr(value):
            """Hopefully pretty robust repr equivalent."""
            # this is pretty horrible but should always return *something*
            try:
                return pydoc.text.repr(value)
            except KeyboardInterrupt:
                raise
            except:
                try:
                    return repr(value)
                except KeyboardInterrupt:
                    raise
                except:
                    try:
                        # all still in an except block so we catch
                        # getattr raising
                        name = getattr(value, '__name__', None)
                        if name:
                            # ick, recursion
                            return text_repr(name)
                        klass = getattr(value, '__class__', None)
                        if klass:
                            return '%s instance' % text_repr(klass)
                    except KeyboardInterrupt:
                        raise
                    except:
                        return 'UNRECOVERABLE REPR FAILURE'
        def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
        def nullrepr(value, repr=text_repr): return ''

        # meat of the code begins
        try:
            etype = etype.__name__
        except AttributeError:
            pass

        if self.long_header:
            # Header with the exception type, python version, and date
            pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
            date = time.ctime(time.time())
            
            head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
                                           exc, ' '*(75-len(str(etype))-len(pyver)),
                                           pyver, string.rjust(date, 75) )
            head += "\nA problem occured executing Python code.  Here is the sequence of function"\
                    "\ncalls leading up to the error, with the most recent (innermost) call last."
        else:
            # Simplified header
            head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
                                     string.rjust('Traceback (most recent call last)',
                                                  75 - len(str(etype)) ) )
        frames = []
        # Flush cache before calling inspect.  This helps alleviate some of the
        # problems with python 2.3's inspect.py.
        linecache.checkcache()
        # Drop topmost frames if requested
        try:
            # Try the default getinnerframes and Alex's: Alex's fixes some
            # problems, but it generates empty tracebacks for console errors
            # (5 blanks lines) where none should be returned.
            #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
            #print 'python records:', records # dbg
            records = _fixed_getinnerframes(etb, context,self.tb_offset)
            #print 'alex   records:', records # dbg
        except:

            # FIXME: I've been getting many crash reports from python 2.3
            # users, traceable to inspect.py.  If I can find a small test-case
            # to reproduce this, I should either write a better workaround or
            # file a bug report against inspect (if that's the real problem).
            # So far, I haven't been able to find an isolated example to
            # reproduce the problem.
            inspect_error()
            traceback.print_exc(file=Term.cerr)
            info('\nUnfortunately, your original traceback can not be constructed.\n')
            return ''

        # build some color string templates outside these nested loops
        tpl_link       = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
        tpl_call       = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
                                              ColorsNormal)
        tpl_call_fail  = 'in %s%%s%s(***failed resolving arguments***)%s' % \
                         (Colors.vName, Colors.valEm, ColorsNormal)
        tpl_local_var  = '%s%%s%s' % (Colors.vName, ColorsNormal)
        tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
                                                 Colors.vName, ColorsNormal)
        tpl_name_val   = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
        tpl_line       = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
        tpl_line_em    = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
                                            ColorsNormal)

        # now, loop over all records printing context and info
        abspath = os.path.abspath
        for frame, file, lnum, func, lines, index in records:
            #print '*** record:',file,lnum,func,lines,index  # dbg
            try:
                file = file and abspath(file) or '?'
            except OSError:
                # if file is '<console>' or something not in the filesystem,
                # the abspath call will throw an OSError.  Just ignore it and
                # keep the original file string.
                pass
            link = tpl_link % file
            try:
                args, varargs, varkw, locals = inspect.getargvalues(frame)
            except:
                # This can happen due to a bug in python2.3.  We should be
                # able to remove this try/except when 2.4 becomes a
                # requirement.  Bug details at http://python.org/sf/1005466
                inspect_error()
                traceback.print_exc(file=Term.cerr)
                info("\nIPython's exception reporting continues...\n")
                
            if func == '?':
                call = ''
            else:
                # Decide whether to include variable details or not
                var_repr = self.include_vars and eqrepr or nullrepr
                try:
                    call = tpl_call % (func,inspect.formatargvalues(args,
                                                varargs, varkw,
                                                locals,formatvalue=var_repr))
                except KeyError:
                    # Very odd crash from inspect.formatargvalues().  The
                    # scenario under which it appeared was a call to
                    # view(array,scale) in NumTut.view.view(), where scale had
                    # been defined as a scalar (it should be a tuple). Somehow
                    # inspect messes up resolving the argument list of view()
                    # and barfs out. At some point I should dig into this one
                    # and file a bug report about it.
                    inspect_error()
                    traceback.print_exc(file=Term.cerr)
                    info("\nIPython's exception reporting continues...\n")
                    call = tpl_call_fail % func

            # Initialize a list of names on the current line, which the
            # tokenizer below will populate.
            names = []

            def tokeneater(token_type, token, start, end, line):
                """Stateful tokeneater which builds dotted names.

                The list of names it appends to (from the enclosing scope) can
                contain repeated composite names.  This is unavoidable, since
                there is no way to disambguate partial dotted structures until
                the full list is known.  The caller is responsible for pruning
                the final list of duplicates before using it."""
                
                # build composite names
                if token == '.':
                    try:
                        names[-1] += '.'
                        # store state so the next token is added for x.y.z names
                        tokeneater.name_cont = True
                        return
                    except IndexError:
                        pass
                if token_type == tokenize.NAME and token not in keyword.kwlist:
                    if tokeneater.name_cont:
                        # Dotted names
                        names[-1] += token
                        tokeneater.name_cont = False
                    else:
                        # Regular new names.  We append everything, the caller
                        # will be responsible for pruning the list later.  It's
                        # very tricky to try to prune as we go, b/c composite
                        # names can fool us.  The pruning at the end is easy
                        # to do (or the caller can print a list with repeated
                        # names if so desired.
                        names.append(token)
                elif token_type == tokenize.NEWLINE:
                    raise IndexError
            # we need to store a bit of state in the tokenizer to build
            # dotted names
            tokeneater.name_cont = False

            def linereader(file=file, lnum=[lnum], getline=linecache.getline):
                line = getline(file, lnum[0])
                lnum[0] += 1
                return line

            # Build the list of names on this line of code where the exception
            # occurred.
            try:
                # This builds the names list in-place by capturing it from the
                # enclosing scope.
                tokenize.tokenize(linereader, tokeneater)
            except IndexError:
                # signals exit of tokenizer
                pass
            except tokenize.TokenError,msg:
                _m = ("An unexpected error occurred while tokenizing input\n"
                      "The following traceback may be corrupted or invalid\n"
                      "The error message is: %s\n" % msg)
                error(_m)
            
            # prune names list of duplicates, but keep the right order
            unique_names = uniq_stable(names)

            # Start loop over vars
            lvals = []
            if self.include_vars:
                for name_full in unique_names:
                    name_base = name_full.split('.',1)[0]
                    if name_base in frame.f_code.co_varnames:
                        if locals.has_key(name_base):
                            try:
                                value = repr(eval(name_full,locals))
                            except:
                                value = undefined
                        else:
                            value = undefined
                        name = tpl_local_var % name_full
                    else:
                        if frame.f_globals.has_key(name_base):
                            try:
                                value = repr(eval(name_full,frame.f_globals))
                            except:
                                value = undefined
                        else:
                            value = undefined
                        name = tpl_global_var % name_full
                    lvals.append(tpl_name_val % (name,value))
            if lvals:
                lvals = '%s%s' % (indent,em_normal.join(lvals))
            else:
                lvals = ''

            level = '%s %s\n' % (link,call)

            if index is None:
                frames.append(level)
            else:
                frames.append('%s%s' % (level,''.join(
                    _formatTracebackLines(lnum,index,lines,Colors,lvals,
                                          col_scheme))))
コード例 #18
0
 def result(self, num):
     """result(N) -> return the result of job N."""
     try:
         return self.jobs_all[num].result
     except KeyError:
         error('Job #%s not found' % num)
コード例 #19
0
 def traceback(self, num):
     try:
         self.jobs_all[num].traceback()
     except KeyError:
         error('Job #%s not found' % num)