def exe(self):
        """The process executable path. May also be an empty string."""
        def guess_it(fallback):
            # try to guess exe from cmdline[0] in absence of a native
            # exe representation
            cmdline = self.cmdline
            if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
                exe = cmdline[0]  # the possible exe
                rexe = os.path.realpath(exe)  # ...in case it's a symlink
                if os.path.isabs(rexe) and os.path.isfile(rexe) \
                and os.access(rexe, os.X_OK):
                    return exe
            if isinstance(fallback, AccessDenied):
                raise fallback
            return fallback

        try:
            exe = self._platform_impl.get_process_exe()
        except AccessDenied:
            err = sys.exc_info()[1]
            return guess_it(fallback=err)
        else:
            if not exe:
                # underlying implementation can legitimately return an
                # empty string; if that's the case we don't want to
                # raise AD while guessing from the cmdline
                try:
                    exe = guess_it(fallback=exe)
                except AccessDenied:
                    pass
            return exe

def exe ( self ) : def guess_it ( fallback ) : cmdline = self . cmdline if cmdline and hasattr ( os , 'access' ) and hasattr ( os , 'X_OK' ) : exe = cmdline [ 0 ] rexe = os . path . realpath ( exe ) if os . path . isabs ( rexe ) and os . path . isfile ( rexe ) and os . access ( rexe , os . X_OK ) : return exe if isinstance ( fallback , AccessDenied ) : raise fallback return fallback try : exe = self . _platform_impl . get_process_exe ( ) except AccessDenied : err = sys . exc_info ( ) [ 1 ] return guess_it ( fallback = err ) else : if not exe : try : exe = guess_it ( fallback = exe ) except AccessDenied : pass return exe

The process executable path . May also be an empty string .


def get_children(self, recursive=False):
        """Return the children of this process as a list of Process
        objects.
        If recursive is True return all the parent descendants.

        Example (A == this process):

         A ─┐
            │
            ├─ B (child) ─┐
            │             └─ X (grandchild) ─┐
            │                                └─ Y (great grandchild)
            ├─ C (child)
            └─ D (child)

        >>> p.get_children()
        B, C, D
        >>> p.get_children(recursive=True)
        B, X, Y, C, D

        Note that in the example above if process X disappears
        process Y won't be returned either as the reference to
        process A is lost.
        """
        if not self.is_running():
            name = self._platform_impl._process_name
            raise NoSuchProcess(self.pid, name)

        ret = []
        if not recursive:
            for p in process_iter():
                try:
                    if p.ppid == self.pid:
                        # if child happens to be older than its parent
                        # (self) it means child's PID has been reused
                        if self.create_time <= p.create_time:
                            ret.append(p)
                except NoSuchProcess:
                    pass
        else:
            # construct a dict where 'values' are all the processes
            # having 'key' as their parent
            table = defaultdict(list)
            for p in process_iter():
                try:
                    table[p.ppid].append(p)
                except NoSuchProcess:
                    pass
            # At this point we have a mapping table where table[self.pid]
            # are the current process's children.
            # Below, we look for all descendants recursively, similarly
            # to a recursive function call.
            checkpids = [self.pid]
            for pid in checkpids:
                for child in table[pid]:
                    try:
                        # if child happens to be older than its parent
                        # (self) it means child's PID has been reused
                        intime = self.create_time <= child.create_time
                    except NoSuchProcess:
                        pass
                    else:
                        if intime:
                            ret.append(child)
                            if child.pid not in checkpids:
                                checkpids.append(child.pid)
        return ret

def get_children ( self , recursive = False ) : if not self . is_running ( ) : name = self . _platform_impl . _process_name raise NoSuchProcess ( self . pid , name ) ret = [ ] if not recursive : for p in process_iter ( ) : try : if p . ppid == self . pid : if self . create_time <= p . create_time : ret . append ( p ) except NoSuchProcess : pass else : table = defaultdict ( list ) for p in process_iter ( ) : try : table [ p . ppid ] . append ( p ) except NoSuchProcess : pass checkpids = [ self . pid ] for pid in checkpids : for child in table [ pid ] : try : intime = self . create_time <= child . create_time except NoSuchProcess : pass else : if intime : ret . append ( child ) if child . pid not in checkpids : checkpids . append ( child . pid ) return ret

Return the children of this process as a list of Process objects . If recursive is True return all the parent descendants .


def get_cpu_percent(self, interval=0.1):
        """Return a float representing the current process CPU
        utilization as a percentage.

        When interval is > 0.0 compares process times to system CPU
        times elapsed before and after the interval (blocking).

        When interval is 0.0 or None compares process times to system CPU
        times elapsed since last call, returning immediately.
        In this case is recommended for accuracy that this function be
        called with at least 0.1 seconds between calls.
        """
        blocking = interval is not None and interval > 0.0
        if blocking:
            st1 = sum(cpu_times())
            pt1 = self._platform_impl.get_cpu_times()
            time.sleep(interval)
            st2 = sum(cpu_times())
            pt2 = self._platform_impl.get_cpu_times()
        else:
            st1 = self._last_sys_cpu_times
            pt1 = self._last_proc_cpu_times
            st2 = sum(cpu_times())
            pt2 = self._platform_impl.get_cpu_times()
            if st1 is None or pt1 is None:
                self._last_sys_cpu_times = st2
                self._last_proc_cpu_times = pt2
                return 0.0

        delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system)
        delta_time = st2 - st1
        # reset values for next call in case of interval == None
        self._last_sys_cpu_times = st2
        self._last_proc_cpu_times = pt2

        try:
            # the utilization split between all CPUs
            overall_percent = (delta_proc / delta_time) * 100
        except ZeroDivisionError:
            # interval was too low
            return 0.0
        # the utilization of a single CPU
        single_cpu_percent = overall_percent * NUM_CPUS
        # on posix a percentage > 100 is legitimate
        # http://stackoverflow.com/questions/1032357/comprehending-top-cpu-usage
        # on windows we use this ugly hack to avoid troubles with float
        # precision issues
        if os.name != 'posix':
            if single_cpu_percent > 100.0:
                return 100.0
        return round(single_cpu_percent, 1)

def get_cpu_percent ( self , interval = 0.1 ) : blocking = interval is not None and interval > 0.0 if blocking : st1 = sum ( cpu_times ( ) ) pt1 = self . _platform_impl . get_cpu_times ( ) time . sleep ( interval ) st2 = sum ( cpu_times ( ) ) pt2 = self . _platform_impl . get_cpu_times ( ) else : st1 = self . _last_sys_cpu_times pt1 = self . _last_proc_cpu_times st2 = sum ( cpu_times ( ) ) pt2 = self . _platform_impl . get_cpu_times ( ) if st1 is None or pt1 is None : self . _last_sys_cpu_times = st2 self . _last_proc_cpu_times = pt2 return 0.0 delta_proc = ( pt2 . user - pt1 . user ) + ( pt2 . system - pt1 . system ) delta_time = st2 - st1 self . _last_sys_cpu_times = st2 self . _last_proc_cpu_times = pt2 try : overall_percent = ( delta_proc / delta_time ) * 100 except ZeroDivisionError : return 0.0 single_cpu_percent = overall_percent * NUM_CPUS if os . name != 'posix' : if single_cpu_percent > 100.0 : return 100.0 return round ( single_cpu_percent , 1 )

Return a float representing the current process CPU utilization as a percentage .


def get_memory_percent(self):
        """Compare physical system memory to process resident memory and
        calculate process memory utilization as a percentage.
        """
        rss = self._platform_impl.get_memory_info()[0]
        try:
            return (rss / float(TOTAL_PHYMEM)) * 100
        except ZeroDivisionError:
            return 0.0

def get_memory_percent ( self ) : rss = self . _platform_impl . get_memory_info ( ) [ 0 ] try : return ( rss / float ( TOTAL_PHYMEM ) ) * 100 except ZeroDivisionError : return 0.0

Compare physical system memory to process resident memory and calculate process memory utilization as a percentage .


def get_memory_maps(self, grouped=True):
        """Return process's mapped memory regions as a list of nameduples
        whose fields are variable depending on the platform.

        If 'grouped' is True the mapped regions with the same 'path'
        are grouped together and the different memory fields are summed.

        If 'grouped' is False every mapped region is shown as a single
        entity and the namedtuple will also include the mapped region's
        address space ('addr') and permission set ('perms').
        """
        it = self._platform_impl.get_memory_maps()
        if grouped:
            d = {}
            for tupl in it:
                path = tupl[2]
                nums = tupl[3:]
                try:
                    d[path] = map(lambda x, y: x+y, d[path], nums)
                except KeyError:
                    d[path] = nums
            nt = self._platform_impl.nt_mmap_grouped
            return [nt(path, *d[path]) for path in d]
        else:
            nt = self._platform_impl.nt_mmap_ext
            return [nt(*x) for x in it]

def get_memory_maps ( self , grouped = True ) : it = self . _platform_impl . get_memory_maps ( ) if grouped : d = { } for tupl in it : path = tupl [ 2 ] nums = tupl [ 3 : ] try : d [ path ] = map ( lambda x , y : x + y , d [ path ] , nums ) except KeyError : d [ path ] = nums nt = self . _platform_impl . nt_mmap_grouped return [ nt ( path , * d [ path ] ) for path in d ] else : nt = self . _platform_impl . nt_mmap_ext return [ nt ( * x ) for x in it ]

Return process s mapped memory regions as a list of nameduples whose fields are variable depending on the platform .


def is_running(self):
        """Return whether this process is running."""
        if self._gone:
            return False
        try:
            # Checking if pid is alive is not enough as the pid might
            # have been reused by another process.
            # pid + creation time, on the other hand, is supposed to
            # identify a process univocally.
            return self.create_time == \
                   self._platform_impl.get_process_create_time()
        except NoSuchProcess:
            self._gone = True
            return False

def is_running ( self ) : if self . _gone : return False try : return self . create_time == self . _platform_impl . get_process_create_time ( ) except NoSuchProcess : self . _gone = True return False

Return whether this process is running .


def suspend(self):
        """Suspend process execution."""
        # safety measure in case the current process has been killed in
        # meantime and the kernel reused its PID
        if not self.is_running():
            name = self._platform_impl._process_name
            raise NoSuchProcess(self.pid, name)
        # windows
        if hasattr(self._platform_impl, "suspend_process"):
            self._platform_impl.suspend_process()
        else:
            # posix
            self.send_signal(signal.SIGSTOP)

def suspend ( self ) : if not self . is_running ( ) : name = self . _platform_impl . _process_name raise NoSuchProcess ( self . pid , name ) if hasattr ( self . _platform_impl , "suspend_process" ) : self . _platform_impl . suspend_process ( ) else : self . send_signal ( signal . SIGSTOP )


def resume(self):
        """Resume process execution."""
        # safety measure in case the current process has been killed in
        # meantime and the kernel reused its PID
        if not self.is_running():
            name = self._platform_impl._process_name
            raise NoSuchProcess(self.pid, name)
        # windows
        if hasattr(self._platform_impl, "resume_process"):
            self._platform_impl.resume_process()
        else:
            # posix
            self.send_signal(signal.SIGCONT)

def resume ( self ) : if not self . is_running ( ) : name = self . _platform_impl . _process_name raise NoSuchProcess ( self . pid , name ) if hasattr ( self . _platform_impl , "resume_process" ) : self . _platform_impl . resume_process ( ) else : self . send_signal ( signal . SIGCONT )


def kill(self):
        """Kill the current process."""
        # safety measure in case the current process has been killed in
        # meantime and the kernel reused its PID
        if not self.is_running():
            name = self._platform_impl._process_name
            raise NoSuchProcess(self.pid, name)
        if os.name == 'posix':
            self.send_signal(signal.SIGKILL)
        else:
            self._platform_impl.kill_process()

def kill ( self ) : if not self . is_running ( ) : name = self . _platform_impl . _process_name raise NoSuchProcess ( self . pid , name ) if os . name == 'posix' : self . send_signal ( signal . SIGKILL ) else : self . _platform_impl . kill_process ( )


def wait(self, timeout=None):
        """Wait for process to terminate and, if process is a children
        of the current one also return its exit code, else None.
        """
        if timeout is not None and not timeout >= 0:
            raise ValueError("timeout must be a positive integer")
        return self._platform_impl.process_wait(timeout)

def
wait
(
self
,
timeout
=
)
:
if
timeout
is
not
and
not
timeout
>=
0
:
raise
ValueError
(
"timeout must be a positive integer"
)
return
self
.
_platform_impl
.
process_wait
(
timeout
)

Wait for process to terminate and if process is a children of the current one also return its exit code else None .


def _wire_kernel(self):
        """Initializes the kernel inside GTK.

        This is meant to run only once at startup, so it does its job and
        returns False to ensure it doesn't get run again by GTK.
        """
        self.gtk_main, self.gtk_main_quit = self._hijack_gtk()
        gobject.timeout_add(int(1000*self.kernel._poll_interval),
                            self.iterate_kernel)
        return False

def _wire_kernel ( self ) : self . gtk_main , self . gtk_main_quit = self . _hijack_gtk ( ) gobject . timeout_add ( int ( 1000 * self . kernel . _poll_interval ) , self . iterate_kernel ) return False

Initializes the kernel inside GTK . This is meant to run only once at startup so it does its job and returns False to ensure it doesn t get run again by GTK .


def _hijack_gtk(self):
        """Hijack a few key functions in GTK for IPython integration.

        Modifies pyGTK's main and main_quit with a dummy so user code does not
        block IPython.  This allows us to use %run to run arbitrary pygtk
        scripts from a long-lived IPython session, and when they attempt to
        start or stop

        Returns
        -------
        The original functions that have been hijacked:
        - gtk.main
        - gtk.main_quit
        """
        def dummy(*args, **kw):
            pass
        # save and trap main and main_quit from gtk
        orig_main, gtk.main = gtk.main, dummy
        orig_main_quit, gtk.main_quit = gtk.main_quit, dummy
        return orig_main, orig_main_quit

def _hijack_gtk ( self ) : def dummy ( * args , ** kw ) : pass orig_main , gtk . main = gtk . main , dummy orig_main_quit , gtk . main_quit = gtk . main_quit , dummy return orig_main , orig_main_quit

Hijack a few key functions in GTK for IPython integration .


def is_shadowed(identifier, ip):
    """Is the given identifier defined in one of the namespaces which shadow
    the alias and magic namespaces?  Note that an identifier is different
    than ifun, because it can not contain a '.' character."""
    # This is much safer than calling ofind, which can change state
    return (identifier in ip.user_ns \
            or identifier in ip.user_global_ns \
            or identifier in ip.ns_table['builtin'])

def is_shadowed ( identifier , ip ) : return ( identifier in ip . user_ns or identifier in ip . user_global_ns or identifier in ip . ns_table [ 'builtin' ] )

Is the given identifier defined in one of the namespaces which shadow the alias and magic namespaces? Note that an identifier is different than ifun because it can not contain a . character .


def init_transformers(self):
        """Create the default transformers."""
        self._transformers = []
        for transformer_cls in _default_transformers:
            transformer_cls(
                shell=self.shell, prefilter_manager=self, config=self.config
            )

def init_transformers ( self ) : self . _transformers = [ ] for transformer_cls in _default_transformers : transformer_cls ( shell = self . shell , prefilter_manager = self , config = self . config )


def register_transformer(self, transformer):
        """Register a transformer instance."""
        if transformer not in self._transformers:
            self._transformers.append(transformer)
            self.sort_transformers()

def register_transformer ( self , transformer ) : if transformer not in self . _transformers : self . _transformers . append ( transformer ) self . sort_transformers ( )


def unregister_transformer(self, transformer):
        """Unregister a transformer instance."""
        if transformer in self._transformers:
            self._transformers.remove(transformer)

def unregister_transformer ( self , transformer ) : if transformer in self . _transformers : self . _transformers . remove ( transformer )


def init_checkers(self):
        """Create the default checkers."""
        self._checkers = []
        for checker in _default_checkers:
            checker(
                shell=self.shell, prefilter_manager=self, config=self.config
            )

def init_checkers ( self ) : self . _checkers = [ ] for checker in _default_checkers : checker ( shell = self . shell , prefilter_manager = self , config = self . config )


def register_checker(self, checker):
        """Register a checker instance."""
        if checker not in self._checkers:
            self._checkers.append(checker)
            self.sort_checkers()

def register_checker ( self , checker ) : if checker not in self . _checkers : self . _checkers . append ( checker ) self . sort_checkers ( )


def unregister_checker(self, checker):
        """Unregister a checker instance."""
        if checker in self._checkers:
            self._checkers.remove(checker)

def unregister_checker ( self , checker ) : if checker in self . _checkers : self . _checkers . remove ( checker )


def init_handlers(self):
        """Create the default handlers."""
        self._handlers = {}
        self._esc_handlers = {}
        for handler in _default_handlers:
            handler(
                shell=self.shell, prefilter_manager=self, config=self.config
            )

def init_handlers ( self ) : self . _handlers = { } self . _esc_handlers = { } for handler in _default_handlers : handler ( shell = self . shell , prefilter_manager = self , config = self . config )


def register_handler(self, name, handler, esc_strings):
        """Register a handler instance by name with esc_strings."""
        self._handlers[name] = handler
        for esc_str in esc_strings:
            self._esc_handlers[esc_str] = handler

def register_handler ( self , name , handler , esc_strings ) : self . _handlers [ name ] = handler for esc_str in esc_strings : self . _esc_handlers [ esc_str ] = handler

Register a handler instance by name with esc_strings .


def unregister_handler(self, name, handler, esc_strings):
        """Unregister a handler instance by name with esc_strings."""
        try:
            del self._handlers[name]
        except KeyError:
            pass
        for esc_str in esc_strings:
            h = self._esc_handlers.get(esc_str)
            if h is handler:
                del self._esc_handlers[esc_str]

def unregister_handler ( self , name , handler , esc_strings ) : try : del self . _handlers [ name ] except KeyError : pass for esc_str in esc_strings : h = self . _esc_handlers . get ( esc_str ) if h is handler : del self . _esc_handlers [ esc_str ]

Unregister a handler instance by name with esc_strings .


def prefilter_line_info(self, line_info):
        """Prefilter a line that has been converted to a LineInfo object.

        This implements the checker/handler part of the prefilter pipe.
        """
        # print "prefilter_line_info: ", line_info
        handler = self.find_handler(line_info)
        return handler.handle(line_info)

def prefilter_line_info ( self , line_info ) : handler = self . find_handler ( line_info ) return handler . handle ( line_info )

Prefilter a line that has been converted to a LineInfo object .


def find_handler(self, line_info):
        """Find a handler for the line_info by trying checkers."""
        for checker in self.checkers:
            if checker.enabled:
                handler = checker.check(line_info)
                if handler:
                    return handler
        return self.get_handler_by_name('normal')

def find_handler ( self , line_info ) : for checker in self . checkers : if checker . enabled : handler = checker . check ( line_info ) if handler : return handler return self . get_handler_by_name ( 'normal' )

Find a handler for the line_info by trying checkers .


def transform_line(self, line, continue_prompt):
        """Calls the enabled transformers in order of increasing priority."""
        for transformer in self.transformers:
            if transformer.enabled:
                line = transformer.transform(line, continue_prompt)
        return line

def transform_line ( self , line , continue_prompt ) : for transformer in self . transformers : if transformer . enabled : line = transformer . transform ( line , continue_prompt ) return line

Calls the enabled transformers in order of increasing priority .


def prefilter_line(self, line, continue_prompt=False):
        """Prefilter a single input line as text.

        This method prefilters a single line of text by calling the
        transformers and then the checkers/handlers.
        """

        # print "prefilter_line: ", line, continue_prompt
        # All handlers *must* return a value, even if it's blank ('').

        # save the line away in case we crash, so the post-mortem handler can
        # record it
        self.shell._last_input_line = line

        if not line:
            # Return immediately on purely empty lines, so that if the user
            # previously typed some whitespace that started a continuation
            # prompt, he can break out of that loop with just an empty line.
            # This is how the default python prompt works.
            return ''

        # At this point, we invoke our transformers.
        if not continue_prompt or (continue_prompt and self.multi_line_specials):
            line = self.transform_line(line, continue_prompt)

        # Now we compute line_info for the checkers and handlers
        line_info = LineInfo(line, continue_prompt)

        # the input history needs to track even empty lines
        stripped = line.strip()

        normal_handler = self.get_handler_by_name('normal')
        if not stripped:
            if not continue_prompt:
                self.shell.displayhook.prompt_count -= 1

            return normal_handler.handle(line_info)

        # special handlers are only allowed for single line statements
        if continue_prompt and not self.multi_line_specials:
            return normal_handler.handle(line_info)

        prefiltered = self.prefilter_line_info(line_info)
        # print "prefiltered line: %r" % prefiltered
        return prefiltered

def prefilter_line ( self , line , continue_prompt = False ) : self . shell . _last_input_line = line if not line : return '' if not continue_prompt or ( continue_prompt and self . multi_line_specials ) : line = self . transform_line ( line , continue_prompt ) line_info = LineInfo ( line , continue_prompt ) stripped = line . strip ( ) normal_handler = self . get_handler_by_name ( 'normal' ) if not stripped : if not continue_prompt : self . shell . displayhook . prompt_count -= 1 return normal_handler . handle ( line_info ) if continue_prompt and not self . multi_line_specials : return normal_handler . handle ( line_info ) prefiltered = self . prefilter_line_info ( line_info ) return prefiltered


def prefilter_lines(self, lines, continue_prompt=False):
        """Prefilter multiple input lines of text.

        This is the main entry point for prefiltering multiple lines of
        input.  This simply calls :meth:`prefilter_line` for each line of
        input.

        This covers cases where there are multiple lines in the user entry,
        which is the case when the user goes back to a multiline history
        entry and presses enter.
        """
        llines = lines.rstrip('\n').split('\n')
        # We can get multiple lines in one shot, where multiline input 'blends'
        # into one line, in cases like recalling from the readline history
        # buffer.  We need to make sure that in such cases, we correctly
        # communicate downstream which line is first and which are continuation
        # ones.
        if len(llines) > 1:
            out = '\n'.join([self.prefilter_line(line, lnum>0)
                             for lnum, line in enumerate(llines) ])
        else:
            out = self.prefilter_line(llines[0], continue_prompt)

        return out

def prefilter_lines ( self , lines , continue_prompt = False ) : llines = lines . rstrip ( '\n' ) . split ( '\n' ) if len ( llines ) > 1 : out = '\n' . join ( [ self . prefilter_line ( line , lnum > 0 ) for lnum , line in enumerate ( llines ) ] ) else : out = self . prefilter_line ( llines [ 0 ] , continue_prompt ) return out

Prefilter multiple input lines of text .


def check(self, line_info):
        "Instances of IPyAutocall in user_ns get autocalled immediately"
        obj = self.shell.user_ns.get(line_info.ifun, None)
        if isinstance(obj, IPyAutocall):
            obj.set_ip(self.shell)
            return self.prefilter_manager.get_handler_by_name('auto')
        else:
            return None


def check(self, line_info):
        "Allow ! and !! in multi-line statements if multi_line_specials is on"
        # Note that this one of the only places we check the first character of
        # ifun and *not* the pre_char.  Also note that the below test matches
        # both ! and !!.
        if line_info.continue_prompt \
            and self.prefilter_manager.multi_line_specials:
                if line_info.esc == ESC_MAGIC:
                    return self.prefilter_manager.get_handler_by_name('magic')
        else:
            return None

Allow ! and !! in multi - line statements if multi_line_specials is on


def check(self, line_info):
        """Check for escape character and return either a handler to handle it,
        or None if there is no escape char."""
        if line_info.line[-1] == ESC_HELP \
               and line_info.esc != ESC_SHELL \
               and line_info.esc != ESC_SH_CAP:
            # the ? can be at the end, but *not* for either kind of shell escape,
            # because a ? can be a vaild final char in a shell cmd
            return self.prefilter_manager.get_handler_by_name('help')
        else:
            if line_info.pre:
                return None
            # This returns None like it should if no handler exists
            return self.prefilter_manager.get_handler_by_esc(line_info.esc)

def check ( self , line_info ) : if line_info . line [ - 1 ] == ESC_HELP and line_info . esc != ESC_SHELL and line_info . esc != ESC_SH_CAP : return self . prefilter_manager . get_handler_by_name ( 'help' ) else : if line_info . pre : return None return self . prefilter_manager . get_handler_by_esc ( line_info . esc )

Check for escape character and return either a handler to handle it or None if there is no escape char .


def check(self, line_info):
        "Check if the initital identifier on the line is an alias."
        # Note: aliases can not contain '.'
        head = line_info.ifun.split('.',1)[0]
        if line_info.ifun not in self.shell.alias_manager \
               or head not in self.shell.alias_manager \
               or is_shadowed(head, self.shell):
            return None

        return self.prefilter_manager.get_handler_by_name('alias')

Check if the initital identifier on the line is an alias .


def handle(self, line_info):
        # print "normal: ", line_info
        """Handle normal input lines. Use as a template for handlers."""

        # With autoindent on, we need some way to exit the input loop, and I
        # don't want to force the user to have to backspace all the way to
        # clear the line.  The rule will be in this case, that either two
        # lines of pure whitespace in a row, or a line of pure whitespace but
        # of a size different to the indent level, will exit the input loop.
        line = line_info.line
        continue_prompt = line_info.continue_prompt

        if (continue_prompt and
            self.shell.autoindent and
            line.isspace() and
            0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
            line = ''

        return line

def handle ( self , line_info ) : line = line_info . line continue_prompt = line_info . continue_prompt if ( continue_prompt and self . shell . autoindent and line . isspace ( ) and 0 < abs ( len ( line ) - self . shell . indent_current_nsp ) <= 2 ) : line = '' return line

Handle normal input lines . Use as a template for handlers .


def handle(self, line_info):
        """Handle alias input lines. """
        transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
        # pre is needed, because it carries the leading whitespace.  Otherwise
        # aliases won't work in indented sections.
        line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, transformed)

        return line_out

def handle ( self , line_info ) : transformed = self . shell . alias_manager . expand_aliases ( line_info . ifun , line_info . the_rest ) line_out = '%sget_ipython().system(%r)' % ( line_info . pre_whitespace , transformed ) return line_out


def handle(self, line_info):
        """Execute the line in a shell, empty return value"""
        magic_handler = self.prefilter_manager.get_handler_by_name('magic')

        line = line_info.line
        if line.lstrip().startswith(ESC_SH_CAP):
            # rewrite LineInfo's line, ifun and the_rest to properly hold the
            # call to %sx and the actual command to be executed, so
            # handle_magic can work correctly.  Note that this works even if
            # the line is indented, so it handles multi_line_specials
            # properly.
            new_rest = line.lstrip()[2:]
            line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
            line_info.ifun = 'sx'
            line_info.the_rest = new_rest
            return magic_handler.handle(line_info)
        else:
            cmd = line.lstrip().lstrip(ESC_SHELL)
            line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, cmd)
        return line_out

def
handle
(
self
,
line_info
)
:
magic_handler
=
self
.
prefilter_manager
.
get_handler_by_name
(
'magic'
)
line
=
line_info
.
line
if
line
.
lstrip
(
)
.
startswith
(
ESC_SH_CAP
)
:
new_rest
=
line
.
lstrip
(
)
[
2
:
]
line_info
.
line
=
'%ssx %s'
%
(
ESC_MAGIC
,
new_rest
)
line_info
.
ifun
=
'sx'
line_info
.
the_rest
=
new_rest
return
magic_handler
.
handle
(
line_info
)
else
:
cmd
=
line
.
lstrip
(
)
.
lstrip
(
ESC_SHELL
)
line_out
=
'%sget_ipython().system(%r)'
%
(
line_info
.
pre_whitespace
,
cmd
)
return
line_out

Execute the line in a shell empty return value


def handle(self, line_info):
        """Execute magic functions."""
        ifun    = line_info.ifun
        the_rest = line_info.the_rest
        cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace,
                                                    (ifun + " " + the_rest))
        return cmd

def
handle
(
self
,
line_info
)
:
ifun
=
line_info
.
ifun
the_rest
=
line_info
.
the_rest
cmd
=
'%sget_ipython().magic(%r)'
%
(
line_info
.
pre_whitespace
,
(
ifun
+
" "
+
the_rest
)
)
return
cmd


def handle(self, line_info):
        """Handle lines which can be auto-executed, quoting if requested."""
        line    = line_info.line
        ifun    = line_info.ifun
        the_rest = line_info.the_rest
        pre     = line_info.pre
        esc     = line_info.esc
        continue_prompt = line_info.continue_prompt
        obj = line_info.ofind(self.shell)['obj']
        #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest)  # dbg

        # This should only be active for single-line input!
        if continue_prompt:
            return line

        force_auto = isinstance(obj, IPyAutocall)

        # User objects sometimes raise exceptions on attribute access other
        # than AttributeError (we've seen it in the past), so it's safest to be
        # ultra-conservative here and catch all.
        try:
            auto_rewrite = obj.rewrite
        except Exception:
            auto_rewrite = True

        if esc == ESC_QUOTE:
            # Auto-quote splitting on whitespace
            newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
        elif esc == ESC_QUOTE2:
            # Auto-quote whole string
            newcmd = '%s("%s")' % (ifun,the_rest)
        elif esc == ESC_PAREN:
            newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
        else:
            # Auto-paren.
            if force_auto:
                # Don't rewrite if it is already a call.
                do_rewrite = not the_rest.startswith('(')
            else:
                if not the_rest:
                    # We only apply it to argument-less calls if the autocall
                    # parameter is set to 2.
                    do_rewrite = (self.shell.autocall >= 2)
                elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
                    # Don't autocall in this case: item access for an object
                    # which is BOTH callable and implements __getitem__.
                    do_rewrite = False
                else:
                    do_rewrite = True

            # Figure out the rewritten command
            if do_rewrite:
                if the_rest.endswith(';'):
                    newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
                else:
                    newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
            else:
                normal_handler = self.prefilter_manager.get_handler_by_name('normal')
                return normal_handler.handle(line_info)

        # Display the rewritten call
        if auto_rewrite:
            self.shell.auto_rewrite_input(newcmd)

        return newcmd

def
handle
(
self
,
line_info
)
:
line
=
line_info
.
line
ifun
=
line_info
.
ifun
the_rest
=
line_info
.
the_rest
pre
=
line_info
.
pre
esc
=
line_info
.
esc
continue_prompt
=
line_info
.
continue_prompt
obj
=
line_info
.
ofind
(
self
.
shell
)
[
'obj'
]
if
continue_prompt
:
return
line
force_auto
=
isinstance
(
obj
,
IPyAutocall
)
try
:
auto_rewrite
=
obj
.
rewrite
except
Exception
:
auto_rewrite
=
True
if
esc
==
ESC_QUOTE
:
newcmd
=
'%s("%s")'
%
(
ifun
,
'", "'
.
join
(
the_rest
.
split
(
)
)
)
elif
esc
==
ESC_QUOTE2
:
newcmd
=
'%s("%s")'
%
(
ifun
,
the_rest
)
elif
esc
==
ESC_PAREN
:
newcmd
=
'%s(%s)'
%
(
ifun
,
","
.
join
(
the_rest
.
split
(
)
)
)
else
:
if
force_auto
:
do_rewrite
=
not
the_rest
.
startswith
(
'('
)
else
:
if
not
the_rest
:
do_rewrite
=
(
self
.
shell
.
autocall
>=
2
)
elif
the_rest
.
startswith
(
'['
)
and
hasattr
(
obj
,
'__getitem__'
)
:
do_rewrite
=
False
else
:
do_rewrite
=
True
if
do_rewrite
:
if
the_rest
.
endswith
(
';'
)
:
newcmd
=
'%s(%s);'
%
(
ifun
.
rstrip
(
)
,
the_rest
[
:
1
]
)
else
:
newcmd
=
'%s(%s)'
%
(
ifun
.
rstrip
(
)
,
the_rest
)
else
:
normal_handler
=
self
.
prefilter_manager
.
get_handler_by_name
(
'normal'
)
return
normal_handler
.
handle
(
line_info
)
if
auto_rewrite
:
self
.
shell
.
auto_rewrite_input
(
newcmd
)
return
newcmd

Handle lines which can be auto - executed quoting if requested .


def handle(self, line_info):
        """Try to get some help for the object.

        obj? or ?obj   -> basic information.
        obj?? or ??obj -> more details.
        """
        normal_handler = self.prefilter_manager.get_handler_by_name('normal')
        line = line_info.line
        # We need to make sure that we don't process lines which would be
        # otherwise valid python, such as "x=1 # what?"
        try:
            codeop.compile_command(line)
        except SyntaxError:
            # We should only handle as help stuff which is NOT valid syntax
            if line[0]==ESC_HELP:
                line = line[1:]
            elif line[-1]==ESC_HELP:
                line = line[:-1]
            if line:
                #print 'line:<%r>' % line  # dbg
                self.shell.magic('pinfo %s' % line_info.ifun)
            else:
                self.shell.show_usage()
            return '' # Empty string is needed here!
        except:
            raise
            # Pass any other exceptions through to the normal handler
            return normal_handler.handle(line_info)
        else:
            # If the code compiles ok, we should handle it normally
            return normal_handler.handle(line_info)

def
handle
(
self
,
line_info
)
:
normal_handler
=
self
.
prefilter_manager
.
get_handler_by_name
(
'normal'
)
line
=
line_info
.
line
try
:
codeop
.
compile_command
(
line
)
except
SyntaxError
:
if
line
[
0
]
==
ESC_HELP
:
line
=
line
[
1
:
]
elif
line
[
1
]
==
ESC_HELP
:
line
=
line
[
:
1
]
if
line
:
self
.
shell
.
magic
(
'pinfo %s'
%
line_info
.
ifun
)
else
:
self
.
shell
.
show_usage
(
)
return
''
except
:
raise
return
normal_handler
.
handle
(
line_info
)
else
:
return
normal_handler
.
handle
(
line_info
)


def eventFilter(self, obj, event):
        """ Reimplemented to hide on certain key presses and on text edit focus
            changes.
        """
        if obj == self._text_edit:
            etype = event.type()

            if etype == QtCore.QEvent.KeyPress:
                key = event.key()
                if key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
                    self.hide()
                elif key == QtCore.Qt.Key_Escape:
                    self.hide()
                    return True

            elif etype == QtCore.QEvent.FocusOut:
                self.hide()

            elif etype == QtCore.QEvent.Enter:
                self._hide_timer.stop()

            elif etype == QtCore.QEvent.Leave:
                self._leave_event_hide()

        return super(CallTipWidget, self).eventFilter(obj, event)

def eventFilter ( self , obj , event ) : if obj == self . _text_edit : etype = event . type ( ) if etype == QtCore . QEvent . KeyPress : key = event . key ( ) if key in ( QtCore . Qt . Key_Enter , QtCore . Qt . Key_Return ) : self . hide ( ) elif key == QtCore . Qt . Key_Escape : self . hide ( ) return True elif etype == QtCore . QEvent . FocusOut : self . hide ( ) elif etype == QtCore . QEvent . Enter : self . _hide_timer . stop ( ) elif etype == QtCore . QEvent . Leave : self . _leave_event_hide ( ) return super ( CallTipWidget , self ) . eventFilter ( obj , event )

Reimplemented to hide on certain key presses and on text edit focus changes .


def enterEvent(self, event):
        """ Reimplemented to cancel the hide timer.
        """
        super(CallTipWidget, self).enterEvent(event)
        self._hide_timer.stop()

def enterEvent ( self , event ) : super ( CallTipWidget , self ) . enterEvent ( event ) self . _hide_timer . stop ( )

Reimplemented to cancel the hide timer .


def paintEvent(self, event):
        """ Reimplemented to paint the background panel.
        """
        painter = QtGui.QStylePainter(self)
        option = QtGui.QStyleOptionFrame()
        option.initFrom(self)
        painter.drawPrimitive(QtGui.QStyle.PE_PanelTipLabel, option)
        painter.end()

        super(CallTipWidget, self).paintEvent(event)

def paintEvent ( self , event ) : painter = QtGui . QStylePainter ( self ) option = QtGui . QStyleOptionFrame ( ) option . initFrom ( self ) painter . drawPrimitive ( QtGui . QStyle . PE_PanelTipLabel , option ) painter . end ( ) super ( CallTipWidget , self ) . paintEvent ( event )

Reimplemented to paint the background panel .


def show_call_info(self, call_line=None, doc=None, maxlines=20):
        """ Attempts to show the specified call line and docstring at the
            current cursor location. The docstring is possibly truncated for
            length.
        """
        if doc:
            match = re.match("(?:[^\n]*\n){%i}" % maxlines, doc)
            if match:
                doc = doc[:match.end()] + '\n[Documentation continues...]'
        else:
            doc = ''

        if call_line:
            doc = '\n\n'.join([call_line, doc])
        return self.show_tip(doc)

def
show_call_info
(
self
,
call_line
=
,
doc
=
,
maxlines
=
20
)
:
if
doc
:
match
=
re
.
match
(
"(?:[^\n]*\n){%i}"
%
maxlines
,
doc
)
if
match
:
doc
=
doc
[
:
match
.
end
(
)
]
+
'\n[Documentation continues...]'
else
:
doc
=
''
if
call_line
:
doc
=
'\n\n'
.
join
(
[
call_line
,
doc
]
)
return
self
.
show_tip
(
doc
)

Attempts to show the specified call line and docstring at the current cursor location . The docstring is possibly truncated for length .


def show_tip(self, tip):
        """ Attempts to show the specified tip at the current cursor location.
        """
        # Attempt to find the cursor position at which to show the call tip.
        text_edit = self._text_edit
        document = text_edit.document()
        cursor = text_edit.textCursor()
        search_pos = cursor.position() - 1
        self._start_position, _ = self._find_parenthesis(search_pos,
                                                         forward=False)
        if self._start_position == -1:
            return False

        # Set the text and resize the widget accordingly.
        self.setText(tip)
        self.resize(self.sizeHint())

        # Locate and show the widget. Place the tip below the current line
        # unless it would be off the screen.  In that case, decide the best
        # location based trying to minimize the  area that goes off-screen.
        padding = 3 # Distance in pixels between cursor bounds and tip box.
        cursor_rect = text_edit.cursorRect(cursor)
        screen_rect = QtGui.qApp.desktop().screenGeometry(text_edit)
        point = text_edit.mapToGlobal(cursor_rect.bottomRight())
        point.setY(point.y() + padding)
        tip_height = self.size().height()
        tip_width = self.size().width()

        vertical = 'bottom'
        horizontal = 'Right'
        if point.y() + tip_height > screen_rect.height():
            point_ = text_edit.mapToGlobal(cursor_rect.topRight())
            # If tip is still off screen, check if point is in top or bottom
            # half of screen.
            if point_.y() - tip_height < padding:
                # If point is in upper half of screen, show tip below it.
                # otherwise above it.
                if 2*point.y() < screen_rect.height():
                    vertical = 'bottom'
                else:
                    vertical = 'top'
            else:
                vertical = 'top'
        if point.x() + tip_width > screen_rect.width():
            point_ = text_edit.mapToGlobal(cursor_rect.topRight())
            # If tip is still off-screen, check if point is in the right or
            # left half of the screen.
            if point_.x() - tip_width < padding:
                if 2*point.x() < screen_rect.width():
                    horizontal = 'Right'
                else:
                    horizontal = 'Left'
            else:
                horizontal = 'Left'
        pos = getattr(cursor_rect, '%s%s' %(vertical, horizontal))
        point = text_edit.mapToGlobal(pos())
        if vertical == 'top':
            point.setY(point.y() - tip_height - padding)
        if horizontal == 'Left':
            point.setX(point.x() - tip_width - padding)

        self.move(point)
        self.show()
        return True

def show_tip ( self , tip ) : text_edit = self . _text_edit document = text_edit . document ( ) cursor = text_edit . textCursor ( ) search_pos = cursor . position ( ) - 1 self . _start_position , _ = self . _find_parenthesis ( search_pos , forward = False ) if self . _start_position == - 1 : return False self . setText ( tip ) self . resize ( self . sizeHint ( ) ) padding = 3 cursor_rect = text_edit . cursorRect ( cursor ) screen_rect = QtGui . qApp . desktop ( ) . screenGeometry ( text_edit ) point = text_edit . mapToGlobal ( cursor_rect . bottomRight ( ) ) point . setY ( point . y ( ) + padding ) tip_height = self . size ( ) . height ( ) tip_width = self . size ( ) . width ( ) vertical = 'bottom' horizontal = 'Right' if point . y ( ) + tip_height > screen_rect . height ( ) : point_ = text_edit . mapToGlobal ( cursor_rect . topRight ( ) ) if point_ . y ( ) - tip_height < padding : if 2 * point . y ( ) < screen_rect . height ( ) : vertical = 'bottom' else : vertical = 'top' else : vertical = 'top' if point . x ( ) + tip_width > screen_rect . width ( ) : point_ = text_edit . mapToGlobal ( cursor_rect . topRight ( ) ) if point_ . x ( ) - tip_width < padding : if 2 * point . x ( ) < screen_rect . width ( ) : horizontal = 'Right' else : horizontal = 'Left' else : horizontal = 'Left' pos = getattr ( cursor_rect , '%s%s' % ( vertical , horizontal ) ) point = text_edit . mapToGlobal ( pos ( ) ) if vertical == 'top' : point . setY ( point . y ( ) - tip_height - padding ) if horizontal == 'Left' : point . setX ( point . x ( ) - tip_width - padding ) self . move ( point ) self . show ( ) return True

Attempts to show the specified tip at the current cursor location .


def _cursor_position_changed(self):
        """ Updates the tip based on user cursor movement.
        """
        cursor = self._text_edit.textCursor()
        if cursor.position() <= self._start_position:
            self.hide()
        else:
            position, commas = self._find_parenthesis(self._start_position + 1)
            if position != -1:
                self.hide()

def _cursor_position_changed ( self ) : cursor = self . _text_edit . textCursor ( ) if cursor . position ( ) <= self . _start_position : self . hide ( ) else : position , commas = self . _find_parenthesis ( self . _start_position + 1 ) if position != - 1 : self . hide ( )

Updates the tip based on user cursor movement .


def proxied_attribute(local_attr, proxied_attr, doc):
    """Create a property that proxies attribute ``proxied_attr`` through
    the local attribute ``local_attr``.
    """
    def fget(self):
        return getattr(getattr(self, local_attr), proxied_attr)
    def fset(self, value):
        setattr(getattr(self, local_attr), proxied_attr, value)
    def fdel(self):
        delattr(getattr(self, local_attr), proxied_attr)
    return property(fget, fset, fdel, doc)

def proxied_attribute ( local_attr , proxied_attr , doc ) : def fget ( self ) : return getattr ( getattr ( self , local_attr ) , proxied_attr ) def fset ( self , value ) : setattr ( getattr ( self , local_attr ) , proxied_attr , value ) def fdel ( self ) : delattr ( getattr ( self , local_attr ) , proxied_attr ) return property ( fget , fset , fdel , doc )

Create a property that proxies attribute proxied_attr through the local attribute local_attr .


def canonicalize_path(cwd, path):
    """
    Canonicalizes a path relative to a given working directory.  That
    is, the path, if not absolute, is interpreted relative to the
    working directory, then converted to absolute form.

    :param cwd: The working directory.
    :param path: The path to canonicalize.

    :returns: The absolute path.
    """

    if not os.path.isabs(path):
        path = os.path.join(cwd, path)

    return os.path.abspath(path)

def canonicalize_path ( cwd , path ) : if not os . path . isabs ( path ) : path = os . path . join ( cwd , path ) return os . path . abspath ( path )

Canonicalizes a path relative to a given working directory . That is the path if not absolute is interpreted relative to the working directory then converted to absolute form .


def schema_validate(instance, schema, exc_class, *prefix, **kwargs):
    """
    Schema validation helper.  Performs JSONSchema validation.  If a
    schema validation error is encountered, an exception of the
    designated class is raised with the validation error message
    appropriately simplified and passed as the sole positional
    argument.

    :param instance: The object to schema validate.
    :param schema: The schema to use for validation.
    :param exc_class: The exception class to raise instead of the
                      ``jsonschema.ValidationError`` exception.
    :param prefix: Positional arguments are interpreted as a list of
                   keys to prefix to the path contained in the
                   validation error.
    :param kwargs: Keyword arguments to pass to the exception
                   constructor.
    """

    try:
        # Do the validation
        jsonschema.validate(instance, schema)
    except jsonschema.ValidationError as exc:
        # Assemble the path
        path = '/'.join((a if isinstance(a, six.string_types) else '[%d]' % a)
                        for a in itertools.chain(prefix, exc.path))

        # Construct the message
        message = 'Failed to validate "%s": %s' % (path, exc.message)

        # Raise the target exception
        raise exc_class(message, **kwargs)

def
schema_validate
(
instance
,
schema
,
exc_class
,
*
prefix
,
**
kwargs
)
:
try
:
jsonschema
.
validate
(
instance
,
schema
)
except
jsonschema
.
ValidationError
as
exc
:
path
=
'/'
.
join
(
(
a
if
isinstance
(
a
,
six
.
string_types
)
else
'[%d]'
%
a
)
for
a
in
itertools
.
chain
(
prefix
,
exc
.
path
)
)
message
=
'Failed to validate "%s": %s'
%
(
path
,
exc
.
message
)
raise
exc_class
(
message
,
**
kwargs
)

Schema validation helper . Performs JSONSchema validation . If a schema validation error is encountered an exception of the designated class is raised with the validation error message appropriately simplified and passed as the sole positional argument .


def masked(self):
        """
        Retrieve a read-only subordinate mapping.  All values are
        stringified, and sensitive values are masked.  The subordinate
        mapping implements the context manager protocol for
        convenience.
        """

        if self._masked is None:
            self._masked = MaskedDict(self)

        return self._masked

def masked ( self ) : if self . _masked is None : self . _masked = MaskedDict ( self ) return self . _masked

Retrieve a read - only subordinate mapping . All values are stringified and sensitive values are masked . The subordinate mapping implements the context manager protocol for convenience .


def virtualenv_no_global():
    """
    Return True if in a venv and no system site packages.
    """
    #this mirrors the logic in virtualenv.py for locating the no-global-site-packages.txt file
    site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))
    no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt')
    if running_under_virtualenv() and os.path.isfile(no_global_file):
        return True

def virtualenv_no_global ( ) : site_mod_dir = os . path . dirname ( os . path . abspath ( site . __file__ ) ) no_global_file = os . path . join ( site_mod_dir , 'no-global-site-packages.txt' ) if running_under_virtualenv ( ) and os . path . isfile ( no_global_file ) : return True

Return True if in a venv and no system site packages .


def pwordfreq(view, fnames):
    """Parallel word frequency counter.

    view - An IPython DirectView
    fnames - The filenames containing the split data.
    """
    assert len(fnames) == len(view.targets)
    view.scatter('fname', fnames, flatten=True)
    ar = view.apply(wordfreq, Reference('fname'))
    freqs_list = ar.get()
    word_set = set()
    for f in freqs_list:
        word_set.update(f.keys())
    freqs = dict(zip(word_set, repeat(0)))
    for f in freqs_list:
        for word, count in f.iteritems():
            freqs[word] += count
    return freqs

def pwordfreq ( view , fnames ) : assert len ( fnames ) == len ( view . targets ) view . scatter ( 'fname' , fnames , flatten = True ) ar = view . apply ( wordfreq , Reference ( 'fname' ) ) freqs_list = ar . get ( ) word_set = set ( ) for f in freqs_list : word_set . update ( f . keys ( ) ) freqs = dict ( zip ( word_set , repeat ( 0 ) ) ) for f in freqs_list : for word , count in f . iteritems ( ) : freqs [ word ] += count return freqs

Parallel word frequency counter . view - An IPython DirectView fnames - The filenames containing the split data .


def view_decorator(function_decorator):
	"""Convert a function based decorator into a class based decorator usable
	on class based Views.

	Can't subclass the `View` as it breaks inheritance (super in particular),
	so we monkey-patch instead.

	Based on http://stackoverflow.com/a/8429311
	"""

	def simple_decorator(View):
		View.dispatch = method_decorator(function_decorator)(View.dispatch)
		return View

	return simple_decorator

def view_decorator ( function_decorator ) : def simple_decorator ( View ) : View . dispatch = method_decorator ( function_decorator ) ( View . dispatch ) return View return simple_decorator

Convert a function based decorator into a class based decorator usable on class based Views .


def default_aliases():
    """Return list of shell aliases to auto-define.
    """
    # Note: the aliases defined here should be safe to use on a kernel
    # regardless of what frontend it is attached to.  Frontends that use a
    # kernel in-process can define additional aliases that will only work in
    # their case.  For example, things like 'less' or 'clear' that manipulate
    # the terminal should NOT be declared here, as they will only work if the
    # kernel is running inside a true terminal, and not over the network.

    if os.name == 'posix':
        default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
                           ('mv', 'mv -i'), ('rm', 'rm -i'), ('cp', 'cp -i'),
                           ('cat', 'cat'),
                           ]
        # Useful set of ls aliases.  The GNU and BSD options are a little
        # different, so we make aliases that provide as similar as possible
        # behavior in ipython, by passing the right flags for each platform
        if sys.platform.startswith('linux'):
            ls_aliases = [('ls', 'ls -F --color'),
                          # long ls
                          ('ll', 'ls -F -o --color'),
                          # ls normal files only
                          ('lf', 'ls -F -o --color %l | grep ^-'),
                          # ls symbolic links
                          ('lk', 'ls -F -o --color %l | grep ^l'),
                          # directories or links to directories,
                          ('ldir', 'ls -F -o --color %l | grep /$'),
                          # things which are executable
                          ('lx', 'ls -F -o --color %l | grep ^-..x'),
                          ]
        else:
            # BSD, OSX, etc.
            ls_aliases = [('ls', 'ls -F'),
                          # long ls
                          ('ll', 'ls -F -l'),
                          # ls normal files only
                          ('lf', 'ls -F -l %l | grep ^-'),
                          # ls symbolic links
                          ('lk', 'ls -F -l %l | grep ^l'),
                          # directories or links to directories,
                          ('ldir', 'ls -F -l %l | grep /$'),
                          # things which are executable
                          ('lx', 'ls -F -l %l | grep ^-..x'),
                          ]
        default_aliases = default_aliases + ls_aliases
    elif os.name in ['nt', 'dos']:
        default_aliases = [('ls', 'dir /on'),
                           ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
                           ('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
                           ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
                           ]
    else:
        default_aliases = []

    return default_aliases

def
default_aliases
(
)
:
if
os
.
name
==
'posix'
:
default_aliases
=
[
(
'mkdir'
,
'mkdir'
)
,
(
'rmdir'
,
'rmdir'
)
,
(
'mv'
,
'mv -i'
)
,
(
'rm'
,
'rm -i'
)
,
(
'cp'
,
'cp -i'
)
,
(
'cat'
,
'cat'
)
,
]
if
sys
.
platform
.
startswith
(
'linux'
)
:
ls_aliases
=
[
(
'ls'
,
'ls -F --color'
)
,
(
'll'
,
'ls -F -o --color'
)
,
(
'lf'
,
'ls -F -o --color %l | grep ^-'
)
,
(
'lk'
,
'ls -F -o --color %l | grep ^l'
)
,
(
'ldir'
,
'ls -F -o --color %l | grep /$'
)
,
(
'lx'
,
'ls -F -o --color %l | grep ^-..x'
)
,
]
else
:
ls_aliases
=
[
(
'ls'
,
'ls -F'
)
,
(
'll'
,
'ls -F -l'
)
,
(
'lf'
,
'ls -F -l %l | grep ^-'
)
,
(
'lk'
,
'ls -F -l %l | grep ^l'
)
,
(
'ldir'
,
'ls -F -l %l | grep /$'
)
,
(
'lx'
,
'ls -F -l %l | grep ^-..x'
)
,
]
default_aliases
=
default_aliases
+
ls_aliases
elif
os
.
name
in
[
'nt'
,
'dos'
]
:
default_aliases
=
[
(
'ls'
,
'dir /on'
)
,
(
'ddir'
,
'dir /ad /on'
)
,
(
'ldir'
,
'dir /ad /on'
)
,
(
'mkdir'
,
'mkdir'
)
,
(
'rmdir'
,
'rmdir'
)
,
(
'echo'
,
'echo'
)
,
(
'ren'
,
'ren'
)
,
(
'copy'
,
'copy'
)
,
]
else
:
default_aliases
=
[
]
return
default_aliases

Return list of shell aliases to auto - define .


def soft_define_alias(self, name, cmd):
        """Define an alias, but don't raise on an AliasError."""
        try:
            self.define_alias(name, cmd)
        except AliasError, e:
            error("Invalid alias: %s" % e)

def
soft_define_alias
(
self
,
name
,
cmd
)
:
try
:
self
.
define_alias
(
name
,
cmd
)
except
AliasError
,
e
:
error
(
"Invalid alias: %s"
%
e
)

Define an alias but don t raise on an AliasError .


def define_alias(self, name, cmd):
        """Define a new alias after validating it.

        This will raise an :exc:`AliasError` if there are validation
        problems.
        """
        nargs = self.validate_alias(name, cmd)
        self.alias_table[name] = (nargs, cmd)

def define_alias ( self , name , cmd ) : nargs = self . validate_alias ( name , cmd ) self . alias_table [ name ] = ( nargs , cmd )

Define a new alias after validating it .


def validate_alias(self, name, cmd):
        """Validate an alias and return the its number of arguments."""
        if name in self.no_alias:
            raise InvalidAliasError("The name %s can't be aliased "
                                    "because it is a keyword or builtin." % name)
        if not (isinstance(cmd, basestring)):
            raise InvalidAliasError("An alias command must be a string, "
                                    "got: %r" % cmd)
        nargs = cmd.count('%s')
        if nargs>0 and cmd.find('%l')>=0:
            raise InvalidAliasError('The %s and %l specifiers are mutually '
                                    'exclusive in alias definitions.')
        return nargs

Validate an alias and return the its number of arguments .


def call_alias(self, alias, rest=''):
        """Call an alias given its name and the rest of the line."""
        cmd = self.transform_alias(alias, rest)
        try:
            self.shell.system(cmd)
        except:
            self.shell.showtraceback()

def call_alias ( self , alias , rest = '' ) : cmd = self . transform_alias ( alias , rest ) try : self . shell . system ( cmd ) except : self . shell . showtraceback ( )

Call an alias given its name and the rest of the line .


def transform_alias(self, alias,rest=''):
        """Transform alias to system command string."""
        nargs, cmd = self.alias_table[alias]

        if ' ' in cmd and os.path.isfile(cmd):
            cmd = '"%s"' % cmd

        # Expand the %l special to be the user's input line
        if cmd.find('%l') >= 0:
            cmd = cmd.replace('%l', rest)
            rest = ''
        if nargs==0:
            # Simple, argument-less aliases
            cmd = '%s %s' % (cmd, rest)
        else:
            # Handle aliases with positional arguments
            args = rest.split(None, nargs)
            if len(args) < nargs:
                raise AliasError('Alias <%s> requires %s arguments, %s given.' %
                      (alias, nargs, len(args)))
            cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
        return cmd

Transform alias to system command string .


def expand_alias(self, line):
        """ Expand an alias in the command line

        Returns the provided command line, possibly with the first word
        (command) translated according to alias expansion rules.

        [ipython]|16> _ip.expand_aliases("np myfile.txt")
                 <16> 'q:/opt/np/notepad++.exe myfile.txt'
        """

        pre,_,fn,rest = split_user_input(line)
        res = pre + self.expand_aliases(fn, rest)
        return res

def expand_alias ( self , line ) : pre , _ , fn , rest = split_user_input ( line ) res = pre + self . expand_aliases ( fn , rest ) return res


def autohelp_directive(dirname, arguments, options, content, lineno,
                       content_offset, block_text, state, state_machine):
    """produces rst from nose help"""
    config = Config(parserClass=OptBucket,
                    plugins=BuiltinPluginManager())
    parser = config.getParser(TestProgram.usage())
    rst = ViewList()
    for line in parser.format_help().split('\n'):
        rst.append(line, '<autodoc>')

    rst.append('Options', '<autodoc>')
    rst.append('-------', '<autodoc>')
    rst.append('', '<autodoc>')
    for opt in parser:
        rst.append(opt.options(), '<autodoc>')
        rst.append('   \n', '<autodoc>')
        rst.append('   ' + opt.help + '\n', '<autodoc>')
        rst.append('\n', '<autodoc>')
    node = nodes.section()
    node.document = state.document
    surrounding_title_styles = state.memo.title_styles
    surrounding_section_level = state.memo.section_level
    state.memo.title_styles = []
    state.memo.section_level = 0
    state.nested_parse(rst, 0, node, match_titles=1)
    state.memo.title_styles = surrounding_title_styles
    state.memo.section_level = surrounding_section_level

    return node.children

def
autohelp_directive
(
dirname
,
arguments
,
options
,
content
,
lineno
,
content_offset
,
block_text
,
state
,
state_machine
)
:
config
=
Config
(
parserClass
=
OptBucket
,
plugins
=
BuiltinPluginManager
(
)
)
parser
=
config
.
getParser
(
TestProgram
.
usage
(
)
)
rst
=
ViewList
(
)
for
line
in
parser
.
format_help
(
)
.
split
(
'\n'
)
:
rst
.
append
(
line
,
'<autodoc>'
)
rst
.
append
(
'Options'
,
'<autodoc>'
)
rst
.
append
(
'-------'
,
'<autodoc>'
)
rst
.
append
(
''
,
'<autodoc>'
)
for
opt
in
parser
:
rst
.
append
(
opt
.
options
(
)
,
'<autodoc>'
)
rst
.
append
(
'   \n'
,
'<autodoc>'
)
rst
.
append
(
'   '
+
opt
.
help
+
'\n'
,
'<autodoc>'
)
rst
.
append
(
'\n'
,
'<autodoc>'
)
node
=
nodes
.
section
(
)
node
.
document
=
state
.
document
surrounding_title_styles
=
state
.
memo
.
title_styles
surrounding_section_level
=
state
.
memo
.
section_level
state
.
memo
.
title_styles
=
[
]
state
.
memo
.
section_level
=
0
state
.
nested_parse
(
rst
,
0
,
node
,
match_titles
=
1
)
state
.
memo
.
title_styles
=
surrounding_title_styles
state
.
memo
.
section_level
=
surrounding_section_level
return
node
.
children


def reset_sgr(self):
        """ Reset graphics attributs to their default values.
        """
        self.intensity = 0
        self.italic = False
        self.bold = False
        self.underline = False
        self.foreground_color = None
        self.background_color = None

def reset_sgr ( self ) : self . intensity = 0 self . italic = False self . bold = False self . underline = False self . foreground_color = None self . background_color = None

Reset graphics attributs to their default values .


def split_string(self, string):
        """ Yields substrings for which the same escape code applies.
        """
        self.actions = []
        start = 0

        # strings ending with \r are assumed to be ending in \r\n since
        # \n is appended to output strings automatically.  Accounting
        # for that, here.
        last_char = '\n' if len(string) > 0 and string[-1] == '\n' else None
        string = string[:-1] if last_char is not None else string

        for match in ANSI_OR_SPECIAL_PATTERN.finditer(string):
            raw = string[start:match.start()]
            substring = SPECIAL_PATTERN.sub(self._replace_special, raw)
            if substring or self.actions:
                yield substring
                self.actions = []
            start = match.end()

            groups = filter(lambda x: x is not None, match.groups())
            g0 = groups[0]
            if g0 == '\a':
                self.actions.append(BeepAction('beep'))
                yield None
                self.actions = []
            elif g0 == '\r':
                self.actions.append(CarriageReturnAction('carriage-return'))
                yield None
                self.actions = []
            elif g0 == '\b':
                self.actions.append(BackSpaceAction('backspace'))
                yield None
                self.actions = []
            elif g0 == '\n' or g0 == '\r\n':
                self.actions.append(NewLineAction('newline'))
                yield g0
                self.actions = []
            else:
                params = [ param for param in groups[1].split(';') if param ]
                if g0.startswith('['):
                    # Case 1: CSI code.
                    try:
                        params = map(int, params)
                    except ValueError:
                        # Silently discard badly formed codes.
                        pass
                    else:
                        self.set_csi_code(groups[2], params)

                elif g0.startswith(']'):
                    # Case 2: OSC code.
                    self.set_osc_code(params)

        raw = string[start:]
        substring = SPECIAL_PATTERN.sub(self._replace_special, raw)
        if substring or self.actions:
            yield substring

        if last_char is not None:
            self.actions.append(NewLineAction('newline'))
            yield last_char

def split_string ( self , string ) : self . actions = [ ] start = 0 last_char = '\n' if len ( string ) > 0 and string [ - 1 ] == '\n' else None string = string [ : - 1 ] if last_char is not None else string for match in ANSI_OR_SPECIAL_PATTERN . finditer ( string ) : raw = string [ start : match . start ( ) ] substring = SPECIAL_PATTERN . sub ( self . _replace_special , raw ) if substring or self . actions : yield substring self . actions = [ ] start = match . end ( ) groups = filter ( lambda x : x is not None , match . groups ( ) ) g0 = groups [ 0 ] if g0 == '\a' : self . actions . append ( BeepAction ( 'beep' ) ) yield None self . actions = [ ] elif g0 == '\r' : self . actions . append ( CarriageReturnAction ( 'carriage-return' ) ) yield None self . actions = [ ] elif g0 == '\b' : self . actions . append ( BackSpaceAction ( 'backspace' ) ) yield None self . actions = [ ] elif g0 == '\n' or g0 == '\r\n' : self . actions . append ( NewLineAction ( 'newline' ) ) yield g0 self . actions = [ ] else : params = [ param for param in groups [ 1 ] . split ( ';' ) if param ] if g0 . startswith ( '[' ) : try : params = map ( int , params ) except ValueError : pass else : self . set_csi_code ( groups [ 2 ] , params ) elif g0 . startswith ( ']' ) : self . set_osc_code ( params ) raw = string [ start : ] substring = SPECIAL_PATTERN . sub ( self . _replace_special , raw ) if substring or self . actions : yield substring if last_char is not None : self . actions . append ( NewLineAction ( 'newline' ) ) yield last_char

Yields substrings for which the same escape code applies .


def get_color(self, color, intensity=0):
        """ Returns a QColor for a given color code, or None if one cannot be
            constructed.
        """
        if color is None:
            return None

        # Adjust for intensity, if possible.
        if color < 8 and intensity > 0:
            color += 8

        constructor = self.color_map.get(color, None)
        if isinstance(constructor, basestring):
            # If this is an X11 color name, we just hope there is a close SVG
            # color name. We could use QColor's static method
            # 'setAllowX11ColorNames()', but this is global and only available
            # on X11. It seems cleaner to aim for uniformity of behavior.
            return QtGui.QColor(constructor)

        elif isinstance(constructor, (tuple, list)):
            return QtGui.QColor(*constructor)

        return None

def get_color ( self , color , intensity = 0 ) : if color is None : return None if color < 8 and intensity > 0 : color += 8 constructor = self . color_map . get ( color , None ) if isinstance ( constructor , basestring ) : return QtGui . QColor ( constructor ) elif isinstance ( constructor , ( tuple , list ) ) : return QtGui . QColor ( * constructor ) return None

Returns a QColor for a given color code or None if one cannot be constructed .


def get_format(self):
        """ Returns a QTextCharFormat that encodes the current style attributes.
        """
        format = QtGui.QTextCharFormat()

        # Set foreground color
        qcolor = self.get_color(self.foreground_color, self.intensity)
        if qcolor is not None:
            format.setForeground(qcolor)

        # Set background color
        qcolor = self.get_color(self.background_color, self.intensity)
        if qcolor is not None:
            format.setBackground(qcolor)

        # Set font weight/style options
        if self.bold:
            format.setFontWeight(QtGui.QFont.Bold)
        else:
            format.setFontWeight(QtGui.QFont.Normal)
        format.setFontItalic(self.italic)
        format.setFontUnderline(self.underline)

        return format

def get_format ( self ) : format = QtGui . QTextCharFormat ( ) qcolor = self . get_color ( self . foreground_color , self . intensity ) if qcolor is not None : format . setForeground ( qcolor ) qcolor = self . get_color ( self . background_color , self . intensity ) if qcolor is not None : format . setBackground ( qcolor ) if self . bold : format . setFontWeight ( QtGui . QFont . Bold ) else : format . setFontWeight ( QtGui . QFont . Normal ) format . setFontItalic ( self . italic ) format . setFontUnderline ( self . underline ) return format

Returns a QTextCharFormat that encodes the current style attributes .


def generate(secret, age, **payload):
    """Generate a one-time jwt with an age in seconds"""
    jti = str(uuid.uuid1()) # random id
    if not payload:
        payload = {}
    payload['exp'] = int(time.time() + age)
    payload['jti'] = jti
    return jwt.encode(payload, decode_secret(secret))

def generate ( secret , age , ** payload ) : jti = str ( uuid . uuid1 ( ) ) if not payload : payload = { } payload [ 'exp' ] = int ( time . time ( ) + age ) payload [ 'jti' ] = jti return jwt . encode ( payload , decode_secret ( secret ) )

Generate a one - time jwt with an age in seconds


def mutex(func):
    """use a thread lock on current method, if self.lock is defined"""
    def wrapper(*args, **kwargs):
        """Decorator Wrapper"""
        lock = args[0].lock
        lock.acquire(True)
        try:
            return func(*args, **kwargs)
        except:
            raise
        finally:
            lock.release()

    return wrapper

def mutex ( func ) : def wrapper ( * args , ** kwargs ) : lock = args [ 0 ] . lock lock . acquire ( True ) try : return func ( * args , ** kwargs ) except : raise finally : lock . release ( ) return wrapper

use a thread lock on current method if self . lock is defined


def _clean(self):
        """Run by housekeeper thread"""
        now = time.time()
        for jwt in self.jwts.keys():
            if (now - self.jwts[jwt]) > (self.age * 2):
                del self.jwts[jwt]

def _clean ( self ) : now = time . time ( ) for jwt in self . jwts . keys ( ) : if ( now - self . jwts [ jwt ] ) > ( self . age * 2 ) : del self . jwts [ jwt ]


def already_used(self, tok):
        """has this jwt been used?"""
        if tok in self.jwts:
            return True
        self.jwts[tok] = time.time()
        return False

def already_used ( self , tok ) : if tok in self . jwts : return True self . jwts [ tok ] = time . time ( ) return False


def valid(self, token):
        """is this token valid?"""
        now = time.time()

        if 'Bearer ' in token:
            token = token[7:]

        data = None
        for secret in self.secrets:
            try:
                data = jwt.decode(token, secret)
                break
            except jwt.DecodeError:
                continue
            except jwt.ExpiredSignatureError:
                raise JwtFailed("Jwt expired")

        if not data:
            raise JwtFailed("Jwt cannot be decoded")

        exp = data.get('exp')
        if not exp:
            raise JwtFailed("Jwt missing expiration (exp)")

        if now - exp > self.age:
            raise JwtFailed("Jwt bad expiration - greater than I want to accept")

        jti = data.get('jti')
        if not jti:
            raise JwtFailed("Jwt missing one-time id (jti)")

        if self.already_used(jti):
            raise JwtFailed("Jwt re-use disallowed (jti={})".format(jti))

        return data


def semaphore(count: int, bounded: bool=False):
    '''
    use `Semaphore` to keep func access thread-safety.

    example:

    ``` py
    @semaphore(3)
    def func(): pass
    ```
    '''

    lock_type = threading.BoundedSemaphore if bounded else threading.Semaphore
    lock_obj = lock_type(value=count)

    return with_it(lock_obj)

def semaphore ( count : int , bounded : bool = False ) : lock_type = threading . BoundedSemaphore if bounded else threading . Semaphore lock_obj = lock_type ( value = count ) return with_it ( lock_obj )

use Semaphore to keep func access thread - safety .


def commonprefix(items):
    """Get common prefix for completions

    Return the longest common prefix of a list of strings, but with special
    treatment of escape characters that might precede commands in IPython,
    such as %magic functions. Used in tab completion.

    For a more general function, see os.path.commonprefix
    """
    # the last item will always have the least leading % symbol
    # min / max are first/last in alphabetical order
    first_match  = ESCAPE_RE.match(min(items))
    last_match  = ESCAPE_RE.match(max(items))
    # common suffix is (common prefix of reversed items) reversed
    if first_match and last_match:
        prefix = os.path.commonprefix((first_match.group(0)[::-1], last_match.group(0)[::-1]))[::-1]
    else:
        prefix = ''

    items = [s.lstrip(ESCAPE_CHARS) for s in items]
    return prefix+os.path.commonprefix(items)

def commonprefix ( items ) : first_match = ESCAPE_RE . match ( min ( items ) ) last_match = ESCAPE_RE . match ( max ( items ) ) if first_match and last_match : prefix = os . path . commonprefix ( ( first_match . group ( 0 ) [ : : - 1 ] , last_match . group ( 0 ) [ : : - 1 ] ) ) [ : : - 1 ] else : prefix = '' items = [ s . lstrip ( ESCAPE_CHARS ) for s in items ] return prefix + os . path . commonprefix ( items )


def eventFilter(self, obj, event):
        """ Reimplemented to ensure a console-like behavior in the underlying
            text widgets.
        """
        etype = event.type()
        if etype == QtCore.QEvent.KeyPress:

            # Re-map keys for all filtered widgets.
            key = event.key()
            if self._control_key_down(event.modifiers()) and \
                    key in self._ctrl_down_remap:
                new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
                                            self._ctrl_down_remap[key],
                                            QtCore.Qt.NoModifier)
                QtGui.qApp.sendEvent(obj, new_event)
                return True

            elif obj == self._control:
                return self._event_filter_console_keypress(event)

            elif obj == self._page_control:
                return self._event_filter_page_keypress(event)

        # Make middle-click paste safe.
        elif etype == QtCore.QEvent.MouseButtonRelease and \
                event.button() == QtCore.Qt.MidButton and \
                obj == self._control.viewport():
            cursor = self._control.cursorForPosition(event.pos())
            self._control.setTextCursor(cursor)
            self.paste(QtGui.QClipboard.Selection)
            return True

        # Manually adjust the scrollbars *after* a resize event is dispatched.
        elif etype == QtCore.QEvent.Resize and not self._filter_resize:
            self._filter_resize = True
            QtGui.qApp.sendEvent(obj, event)
            self._adjust_scrollbars()
            self._filter_resize = False
            return True

        # Override shortcuts for all filtered widgets.
        elif etype == QtCore.QEvent.ShortcutOverride and \
                self.override_shortcuts and \
                self._control_key_down(event.modifiers()) and \
                event.key() in self._shortcuts:
            event.accept()

        # Ensure that drags are safe. The problem is that the drag starting
        # logic, which determines whether the drag is a Copy or Move, is locked
        # down in QTextControl. If the widget is editable, which it must be if
        # we're not executing, the drag will be a Move. The following hack
        # prevents QTextControl from deleting the text by clearing the selection
        # when a drag leave event originating from this widget is dispatched.
        # The fact that we have to clear the user's selection is unfortunate,
        # but the alternative--trying to prevent Qt from using its hardwired
        # drag logic and writing our own--is worse.
        elif etype == QtCore.QEvent.DragEnter and \
                obj == self._control.viewport() and \
                event.source() == self._control.viewport():
            self._filter_drag = True
        elif etype == QtCore.QEvent.DragLeave and \
                obj == self._control.viewport() and \
                self._filter_drag:
            cursor = self._control.textCursor()
            cursor.clearSelection()
            self._control.setTextCursor(cursor)
            self._filter_drag = False

        # Ensure that drops are safe.
        elif etype == QtCore.QEvent.Drop and obj == self._control.viewport():
            cursor = self._control.cursorForPosition(event.pos())
            if self._in_buffer(cursor.position()):
                text = event.mimeData().text()
                self._insert_plain_text_into_buffer(cursor, text)

            # Qt is expecting to get something here--drag and drop occurs in its
            # own event loop. Send a DragLeave event to end it.
            QtGui.qApp.sendEvent(obj, QtGui.QDragLeaveEvent())
            return True

        # Handle scrolling of the vsplit pager. This hack attempts to solve
        # problems with tearing of the help text inside the pager window.  This
        # happens only on Mac OS X with both PySide and PyQt. This fix isn't
        # perfect but makes the pager more usable.
        elif etype in self._pager_scroll_events and \
                obj == self._page_control:
            self._page_control.repaint()
            return True
        return super(ConsoleWidget, self).eventFilter(obj, event)

def eventFilter ( self , obj , event ) : etype = event . type ( ) if etype == QtCore . QEvent . KeyPress : key = event . key ( ) if self . _control_key_down ( event . modifiers ( ) ) and key in self . _ctrl_down_remap : new_event = QtGui . QKeyEvent ( QtCore . QEvent . KeyPress , self . _ctrl_down_remap [ key ] , QtCore . Qt . NoModifier ) QtGui . qApp . sendEvent ( obj , new_event ) return True elif obj == self . _control : return self . _event_filter_console_keypress ( event ) elif obj == self . _page_control : return self . _event_filter_page_keypress ( event ) elif etype == QtCore . QEvent . MouseButtonRelease and event . button ( ) == QtCore . Qt . MidButton and obj == self . _control . viewport ( ) : cursor = self . _control . cursorForPosition ( event . pos ( ) ) self . _control . setTextCursor ( cursor ) self . paste ( QtGui . QClipboard . Selection ) return True elif etype == QtCore . QEvent . Resize and not self . _filter_resize : self . _filter_resize = True QtGui . qApp . sendEvent ( obj , event ) self . _adjust_scrollbars ( ) self . _filter_resize = False return True elif etype == QtCore . QEvent . ShortcutOverride and self . override_shortcuts and self . _control_key_down ( event . modifiers ( ) ) and event . key ( ) in self . _shortcuts : event . accept ( ) elif etype == QtCore . QEvent . DragEnter and obj == self . _control . viewport ( ) and event . source ( ) == self . _control . viewport ( ) : self . _filter_drag = True elif etype == QtCore . QEvent . DragLeave and obj == self . _control . viewport ( ) and self . _filter_drag : cursor = self . _control . textCursor ( ) cursor . clearSelection ( ) self . _control . setTextCursor ( cursor ) self . _filter_drag = False elif etype == QtCore . QEvent . Drop and obj == self . _control . viewport ( ) : cursor = self . _control . cursorForPosition ( event . pos ( ) ) if self . _in_buffer ( cursor . position ( ) ) : text = event . mimeData ( ) . text ( ) self . _insert_plain_text_into_buffer ( cursor , text ) QtGui . qApp . sendEvent ( obj , QtGui . QDragLeaveEvent ( ) ) return True elif etype in self . _pager_scroll_events and obj == self . _page_control : self . _page_control . repaint ( ) return True return super ( ConsoleWidget , self ) . eventFilter ( obj , event )

Reimplemented to ensure a console - like behavior in the underlying text widgets .


def sizeHint(self):
        """ Reimplemented to suggest a size that is 80 characters wide and
            25 lines high.
        """
        font_metrics = QtGui.QFontMetrics(self.font)
        margin = (self._control.frameWidth() +
                  self._control.document().documentMargin()) * 2
        style = self.style()
        splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth)

        # Note 1: Despite my best efforts to take the various margins into
        # account, the width is still coming out a bit too small, so we include
        # a fudge factor of one character here.
        # Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
        # to a Qt bug on certain Mac OS systems where it returns 0.
        width = font_metrics.width(' ') * 81 + margin
        width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
        if self.paging == 'hsplit':
            width = width * 2 + splitwidth

        height = font_metrics.height() * 25 + margin
        if self.paging == 'vsplit':
            height = height * 2 + splitwidth

        return QtCore.QSize(width, height)

def
sizeHint
(
self
)
:
font_metrics
=
QtGui
.
QFontMetrics
(
self
.
font
)
margin
=
(
self
.
_control
.
frameWidth
(
)
+
self
.
_control
.
document
(
)
.
documentMargin
(
)
)
*
2
style
=
self
.
style
(
)
splitwidth
=
style
.
pixelMetric
(
QtGui
.
QStyle
.
PM_SplitterWidth
)
width
=
font_metrics
.
width
(
' '
)
*
81
+
margin
width
+=
style
.
pixelMetric
(
QtGui
.
QStyle
.
PM_ScrollBarExtent
)
if
self
.
paging
==
'hsplit'
:
width
=
width
*
2
+
splitwidth
height
=
font_metrics
.
height
(
)
*
25
+
margin
if
self
.
paging
==
'vsplit'
:
height
=
height
*
2
+
splitwidth
return
QtCore
.
QSize
(
width
,
height
)

Reimplemented to suggest a size that is 80 characters wide and 25 lines high .


def can_cut(self):
        """ Returns whether text can be cut to the clipboard.
        """
        cursor = self._control.textCursor()
        return (cursor.hasSelection() and
                self._in_buffer(cursor.anchor()) and
                self._in_buffer(cursor.position()))

def can_cut ( self ) : cursor = self . _control . textCursor ( ) return ( cursor . hasSelection ( ) and self . _in_buffer ( cursor . anchor ( ) ) and self . _in_buffer ( cursor . position ( ) ) )

Returns whether text can be cut to the clipboard .


def can_paste(self):
        """ Returns whether text can be pasted from the clipboard.
        """
        if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
            return bool(QtGui.QApplication.clipboard().text())
        return False

def can_paste ( self ) : if self . _control . textInteractionFlags ( ) & QtCore . Qt . TextEditable : return bool ( QtGui . QApplication . clipboard ( ) . text ( ) ) return False

Returns whether text can be pasted from the clipboard .


def clear(self, keep_input=True):
        """ Clear the console.

        Parameters:
        -----------
        keep_input : bool, optional (default True)
            If set, restores the old input buffer if a new prompt is written.
        """
        if self._executing:
            self._control.clear()
        else:
            if keep_input:
                input_buffer = self.input_buffer
            self._control.clear()
            self._show_prompt()
            if keep_input:
                self.input_buffer = input_buffer

def clear ( self , keep_input = True ) : if self . _executing : self . _control . clear ( ) else : if keep_input : input_buffer = self . input_buffer self . _control . clear ( ) self . _show_prompt ( ) if keep_input : self . input_buffer = input_buffer


def cut(self):
        """ Copy the currently selected text to the clipboard and delete it
            if it's inside the input buffer.
        """
        self.copy()
        if self.can_cut():
            self._control.textCursor().removeSelectedText()

def cut ( self ) : self . copy ( ) if self . can_cut ( ) : self . _control . textCursor ( ) . removeSelectedText ( )

Copy the currently selected text to the clipboard and delete it if it s inside the input buffer .


def execute(self, source=None, hidden=False, interactive=False):
        """ Executes source or the input buffer, possibly prompting for more
        input.

        Parameters:
        -----------
        source : str, optional

            The source to execute. If not specified, the input buffer will be
            used. If specified and 'hidden' is False, the input buffer will be
            replaced with the source before execution.

        hidden : bool, optional (default False)

            If set, no output will be shown and the prompt will not be modified.
            In other words, it will be completely invisible to the user that
            an execution has occurred.

        interactive : bool, optional (default False)

            Whether the console is to treat the source as having been manually
            entered by the user. The effect of this parameter depends on the
            subclass implementation.

        Raises:
        -------
        RuntimeError
            If incomplete input is given and 'hidden' is True. In this case,
            it is not possible to prompt for more input.

        Returns:
        --------
        A boolean indicating whether the source was executed.
        """
        # WARNING: The order in which things happen here is very particular, in
        # large part because our syntax highlighting is fragile. If you change
        # something, test carefully!

        # Decide what to execute.
        if source is None:
            source = self.input_buffer
            if not hidden:
                # A newline is appended later, but it should be considered part
                # of the input buffer.
                source += '\n'
        elif not hidden:
            self.input_buffer = source

        # Execute the source or show a continuation prompt if it is incomplete.
        complete = self._is_complete(source, interactive)
        if hidden:
            if complete:
                self._execute(source, hidden)
            else:
                error = 'Incomplete noninteractive input: "%s"'
                raise RuntimeError(error % source)
        else:
            if complete:
                self._append_plain_text('\n')
                self._input_buffer_executing = self.input_buffer
                self._executing = True
                self._prompt_finished()

                # The maximum block count is only in effect during execution.
                # This ensures that _prompt_pos does not become invalid due to
                # text truncation.
                self._control.document().setMaximumBlockCount(self.buffer_size)

                # Setting a positive maximum block count will automatically
                # disable the undo/redo history, but just to be safe:
                self._control.setUndoRedoEnabled(False)

                # Perform actual execution.
                self._execute(source, hidden)

            else:
                # Do this inside an edit block so continuation prompts are
                # removed seamlessly via undo/redo.
                cursor = self._get_end_cursor()
                cursor.beginEditBlock()
                cursor.insertText('\n')
                self._insert_continuation_prompt(cursor)
                cursor.endEditBlock()

                # Do not do this inside the edit block. It works as expected
                # when using a QPlainTextEdit control, but does not have an
                # effect when using a QTextEdit. I believe this is a Qt bug.
                self._control.moveCursor(QtGui.QTextCursor.End)

        return complete

def
execute
(
self
,
source
=
,
hidden
=
False
,
interactive
=
False
)
:
if
source
is
:
source
=
self
.
input_buffer
if
not
hidden
:
source
+=
'\n'
elif
not
hidden
:
self
.
input_buffer
=
source
complete
=
self
.
_is_complete
(
source
,
interactive
)
if
hidden
:
if
complete
:
self
.
_execute
(
source
,
hidden
)
else
:
error
=
'Incomplete noninteractive input: "%s"'
raise
RuntimeError
(
error
%
source
)
else
:
if
complete
:
self
.
_append_plain_text
(
'\n'
)
self
.
_input_buffer_executing
=
self
.
input_buffer
self
.
_executing
=
True
self
.
_prompt_finished
(
)
self
.
_control
.
document
(
)
.
setMaximumBlockCount
(
self
.
buffer_size
)
self
.
_control
.
setUndoRedoEnabled
(
False
)
self
.
_execute
(
source
,
hidden
)
else
:
cursor
=
self
.
_get_end_cursor
(
)
cursor
.
beginEditBlock
(
)
cursor
.
insertText
(
'\n'
)
self
.
_insert_continuation_prompt
(
cursor
)
cursor
.
endEditBlock
(
)
self
.
_control
.
moveCursor
(
QtGui
.
QTextCursor
.
End
)
return
complete

Executes source or the input buffer possibly prompting for more input .


def _get_input_buffer(self, force=False):
        """ The text that the user has entered entered at the current prompt.

        If the console is currently executing, the text that is executing will
        always be returned.
        """
        # If we're executing, the input buffer may not even exist anymore due to
        # the limit imposed by 'buffer_size'. Therefore, we store it.
        if self._executing and not force:
            return self._input_buffer_executing

        cursor = self._get_end_cursor()
        cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
        input_buffer = cursor.selection().toPlainText()

        # Strip out continuation prompts.
        return input_buffer.replace('\n' + self._continuation_prompt, '\n')

def _get_input_buffer ( self , force = False ) : if self . _executing and not force : return self . _input_buffer_executing cursor = self . _get_end_cursor ( ) cursor . setPosition ( self . _prompt_pos , QtGui . QTextCursor . KeepAnchor ) input_buffer = cursor . selection ( ) . toPlainText ( ) return input_buffer . replace ( '\n' + self . _continuation_prompt , '\n' )

The text that the user has entered entered at the current prompt .


def _set_input_buffer(self, string):
        """ Sets the text in the input buffer.

        If the console is currently executing, this call has no *immediate*
        effect. When the execution is finished, the input buffer will be updated
        appropriately.
        """
        # If we're executing, store the text for later.
        if self._executing:
            self._input_buffer_pending = string
            return

        # Remove old text.
        cursor = self._get_end_cursor()
        cursor.beginEditBlock()
        cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
        cursor.removeSelectedText()

        # Insert new text with continuation prompts.
        self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)
        cursor.endEditBlock()
        self._control.moveCursor(QtGui.QTextCursor.End)

def _set_input_buffer ( self , string ) : if self . _executing : self . _input_buffer_pending = string return cursor = self . _get_end_cursor ( ) cursor . beginEditBlock ( ) cursor . setPosition ( self . _prompt_pos , QtGui . QTextCursor . KeepAnchor ) cursor . removeSelectedText ( ) self . _insert_plain_text_into_buffer ( self . _get_prompt_cursor ( ) , string ) cursor . endEditBlock ( ) self . _control . moveCursor ( QtGui . QTextCursor . End )


def _set_font(self, font):
        """ Sets the base font for the ConsoleWidget to the specified QFont.
        """
        font_metrics = QtGui.QFontMetrics(font)
        self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))

        self._completion_widget.setFont(font)
        self._control.document().setDefaultFont(font)
        if self._page_control:
            self._page_control.document().setDefaultFont(font)

        self.font_changed.emit(font)

def
_set_font
(
self
,
font
)
:
font_metrics
=
QtGui
.
QFontMetrics
(
font
)
self
.
_control
.
setTabStopWidth
(
self
.
tab_width
*
font_metrics
.
width
(
' '
)
)
self
.
_completion_widget
.
setFont
(
font
)
self
.
_control
.
document
(
)
.
setDefaultFont
(
font
)
if
self
.
_page_control
:
self
.
_page_control
.
document
(
)
.
setDefaultFont
(
font
)
self
.
font_changed
.
emit
(
font
)

Sets the base font for the ConsoleWidget to the specified QFont .


def paste(self, mode=QtGui.QClipboard.Clipboard):
        """ Paste the contents of the clipboard into the input region.

        Parameters:
        -----------
        mode : QClipboard::Mode, optional [default QClipboard::Clipboard]

            Controls which part of the system clipboard is used. This can be
            used to access the selection clipboard in X11 and the Find buffer
            in Mac OS. By default, the regular clipboard is used.
        """
        if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
            # Make sure the paste is safe.
            self._keep_cursor_in_buffer()
            cursor = self._control.textCursor()

            # Remove any trailing newline, which confuses the GUI and forces the
            # user to backspace.
            text = QtGui.QApplication.clipboard().text(mode).rstrip()
            self._insert_plain_text_into_buffer(cursor, dedent(text))

def paste ( self , mode = QtGui . QClipboard . Clipboard ) : if self . _control . textInteractionFlags ( ) & QtCore . Qt . TextEditable : self . _keep_cursor_in_buffer ( ) cursor = self . _control . textCursor ( ) text = QtGui . QApplication . clipboard ( ) . text ( mode ) . rstrip ( ) self . _insert_plain_text_into_buffer ( cursor , dedent ( text ) )

Paste the contents of the clipboard into the input region .


def print_(self, printer = None):
        """ Print the contents of the ConsoleWidget to the specified QPrinter.
        """
        if (not printer):
            printer = QtGui.QPrinter()
            if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted):
                return
        self._control.print_(printer)

def print_ ( self , printer = None ) : if ( not printer ) : printer = QtGui . QPrinter ( ) if ( QtGui . QPrintDialog ( printer ) . exec_ ( ) != QtGui . QDialog . Accepted ) : return self . _control . print_ ( printer )

Print the contents of the ConsoleWidget to the specified QPrinter .


def prompt_to_top(self):
        """ Moves the prompt to the top of the viewport.
        """
        if not self._executing:
            prompt_cursor = self._get_prompt_cursor()
            if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
                self._set_cursor(prompt_cursor)
            self._set_top_cursor(prompt_cursor)

def prompt_to_top ( self ) : if not self . _executing : prompt_cursor = self . _get_prompt_cursor ( ) if self . _get_cursor ( ) . blockNumber ( ) < prompt_cursor . blockNumber ( ) : self . _set_cursor ( prompt_cursor ) self . _set_top_cursor ( prompt_cursor )

Moves the prompt to the top of the viewport .


def reset_font(self):
        """ Sets the font to the default fixed-width font for this platform.
        """
        if sys.platform == 'win32':
            # Consolas ships with Vista/Win7, fallback to Courier if needed
            fallback = 'Courier'
        elif sys.platform == 'darwin':
            # OSX always has Monaco
            fallback = 'Monaco'
        else:
            # Monospace should always exist
            fallback = 'Monospace'
        font = get_font(self.font_family, fallback)
        if self.font_size:
            font.setPointSize(self.font_size)
        else:
            font.setPointSize(QtGui.qApp.font().pointSize())
        font.setStyleHint(QtGui.QFont.TypeWriter)
        self._set_font(font)

def reset_font ( self ) : if sys . platform == 'win32' : fallback = 'Courier' elif sys . platform == 'darwin' : fallback = 'Monaco' else : fallback = 'Monospace' font = get_font ( self . font_family , fallback ) if self . font_size : font . setPointSize ( self . font_size ) else : font . setPointSize ( QtGui . qApp . font ( ) . pointSize ( ) ) font . setStyleHint ( QtGui . QFont . TypeWriter ) self . _set_font ( font )

Sets the font to the default fixed - width font for this platform .