INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return a float representing the current process CPU utilization as a percentage.
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)
Compare physical system memory to process resident memory and calculate process memory 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
Return process s mapped memory regions as a list of nameduples whose fields are variable depending on the platform.
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]
Return whether this process is running.
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
Send a signal to process ( see signal module constants ). On Windows only SIGTERM is valid and is treated as an alias for kill ().
def send_signal(self, sig): """Send a signal to process (see signal module constants). On Windows only SIGTERM is valid and is treated as an alias for kill(). """ # 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': try: os.kill(self.pid, sig) except OSError: err = sys.exc_info()[1] name = self._platform_impl._process_name if err.errno == errno.ESRCH: raise NoSuchProcess(self.pid, name) if err.errno == errno.EPERM: raise AccessDenied(self.pid, name) raise else: if sig == signal.SIGTERM: self._platform_impl.kill_process() else: raise ValueError("only SIGTERM is supported on Windows")
Suspend process execution.
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)
Resume process execution.
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)
Kill the current process.
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()
Wait for process to terminate and if process is a children of the current one also return its exit code else None.
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)
Get or set process niceness ( priority ). Deprecated use get_nice () instead.
def nice(self): """Get or set process niceness (priority). Deprecated, use get_nice() instead. """ msg = "this property is deprecated; use Process.get_nice() method instead" warnings.warn(msg, category=DeprecationWarning, stacklevel=2) return self.get_nice()
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 _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
Hijack a few key functions in GTK for IPython integration.
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
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 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'])
Create the default transformers.
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 )
Register a transformer instance.
def register_transformer(self, transformer): """Register a transformer instance.""" if transformer not in self._transformers: self._transformers.append(transformer) self.sort_transformers()
Unregister a transformer instance.
def unregister_transformer(self, transformer): """Unregister a transformer instance.""" if transformer in self._transformers: self._transformers.remove(transformer)
Create the default checkers.
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 )
Register a checker instance.
def register_checker(self, checker): """Register a checker instance.""" if checker not in self._checkers: self._checkers.append(checker) self.sort_checkers()
Unregister a checker instance.
def unregister_checker(self, checker): """Unregister a checker instance.""" if checker in self._checkers: self._checkers.remove(checker)
Create the default handlers.
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 )
Register a handler instance by name with esc_strings.
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
Unregister 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]
Prefilter a line that has been converted to a LineInfo object.
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)
Find a handler for the line_info by trying checkers.
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')
Calls the enabled transformers in order of increasing priority.
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
Prefilter a single input line as text.
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
Prefilter multiple input lines of text.
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
Instances of IPyAutocall in user_ns get autocalled immediately
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
Allow ! and !! in multi - line statements if multi_line_specials is on
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
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 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)
If the ifun is magic and automagic is on run it. Note: normal non - auto magic would already have been triggered via % in check_esc_chars. This just checks for automagic. Also before triggering the magic handler make sure that there is nothing in the user namespace which could shadow it.
def check(self, line_info): """If the ifun is magic, and automagic is on, run it. Note: normal, non-auto magic would already have been triggered via '%' in check_esc_chars. This just checks for automagic. Also, before triggering the magic handler, make sure that there is nothing in the user namespace which could shadow it.""" if not self.shell.automagic or not self.shell.find_magic(line_info.ifun): return None # We have a likely magic method. Make sure we should actually call it. if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: return None head = line_info.ifun.split('.',1)[0] if is_shadowed(head, self.shell): return None return self.prefilter_manager.get_handler_by_name('magic')
Check if the initital identifier on the line is an alias.
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')
If the rest of the line begins with a function call or pretty much any python operator we should simply execute the line ( regardless of whether or not there s a possible autocall expansion ). This avoids spurious ( and very confusing ) geattr () accesses.
def check(self, line_info): """If the 'rest' of the line begins with a function call or pretty much any python operator, we should simply execute the line (regardless of whether or not there's a possible autocall expansion). This avoids spurious (and very confusing) geattr() accesses.""" if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': return self.prefilter_manager.get_handler_by_name('normal') else: return None
Check if the initial word/ function is callable and autocall is on.
def check(self, line_info): "Check if the initial word/function is callable and autocall is on." if not self.shell.autocall: return None oinfo = line_info.ofind(self.shell) # This can mutate state via getattr if not oinfo['found']: return None if callable(oinfo['obj']) \ and (not self.exclude_regexp.match(line_info.the_rest)) \ and self.function_name_regexp.match(line_info.ifun): return self.prefilter_manager.get_handler_by_name('auto') else: return None
Handle normal input lines. Use as a template for handlers.
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
Handle alias input lines.
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
Execute the line in a shell empty return value
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
Execute magic functions.
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
Handle lines which can be auto - executed quoting if requested.
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
Try to get some help for the object.
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)
Reimplemented to hide on certain key presses and on text edit focus changes.
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)
Reimplemented to cancel the hide timer.
def enterEvent(self, event): """ Reimplemented to cancel the hide timer. """ super(CallTipWidget, self).enterEvent(event) self._hide_timer.stop()
Reimplemented to paint the background panel.
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)
Attempts to show the specified call line and docstring at the current cursor location. The docstring is possibly truncated for length.
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)
Attempts to show the specified tip at the current cursor location.
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
If forward is True ( resp. False ) proceed forwards ( resp. backwards ) through the line that contains position until an unmatched closing ( resp. opening ) parenthesis is found. Returns a tuple containing the position of this parenthesis ( or - 1 if it is not found ) and the number commas ( at depth 0 ) found along the way.
def _find_parenthesis(self, position, forward=True): """ If 'forward' is True (resp. False), proceed forwards (resp. backwards) through the line that contains 'position' until an unmatched closing (resp. opening) parenthesis is found. Returns a tuple containing the position of this parenthesis (or -1 if it is not found) and the number commas (at depth 0) found along the way. """ commas = depth = 0 document = self._text_edit.document() char = document.characterAt(position) # Search until a match is found or a non-printable character is # encountered. while category(char) != 'Cc' and position > 0: if char == ',' and depth == 0: commas += 1 elif char == ')': if forward and depth == 0: break depth += 1 elif char == '(': if not forward and depth == 0: break depth -= 1 position += 1 if forward else -1 char = document.characterAt(position) else: position = -1 return position, commas
Hides the tooltip after some time has passed ( assuming the cursor is not over the tooltip ).
def _leave_event_hide(self): """ Hides the tooltip after some time has passed (assuming the cursor is not over the tooltip). """ if (not self._hide_timer.isActive() and # If Enter events always came after Leave events, we wouldn't need # this check. But on Mac OS, it sometimes happens the other way # around when the tooltip is created. QtGui.qApp.topLevelAt(QtGui.QCursor.pos()) != self): self._hide_timer.start(300, self)
Updates the tip based on user cursor movement.
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()
Create a property that proxies attribute proxied_attr through the local attribute local_attr.
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)
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 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)
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 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)
Iterate over a priority dictionary. A priority dictionary is a dictionary keyed by integer priority with the values being lists of objects. This generator will iterate over the dictionary in priority order ( from lowest integer value to highest integer value ) yielding each object in the lists in turn.
def iter_prio_dict(prio_dict): """ Iterate over a priority dictionary. A priority dictionary is a dictionary keyed by integer priority, with the values being lists of objects. This generator will iterate over the dictionary in priority order (from lowest integer value to highest integer value), yielding each object in the lists in turn. :param prio_dict: A priority dictionary, as described above. :returns: An iterator that yields each object in the correct order, based on priority and ordering within the priority values. """ for _prio, objs in sorted(prio_dict.items(), key=lambda x: x[0]): for obj in objs: yield obj
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 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
Build a file path from * paths * and return the contents.
def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as file_handler: return file_handler.read()
Return True if in a venv and no system site packages.
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
Parallel word frequency counter. view - An IPython DirectView fnames - The filenames containing the split data.
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
Convert a function based decorator into a class based decorator usable on class based Views.
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
Return list of shell aliases to auto - define.
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
Define an alias but don t raise on an AliasError.
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)
Define a new alias after validating it.
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)
Validate an alias and return the its number of arguments.
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
Call an alias given its name and the rest of the line.
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()
Transform alias to system command string.
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
Expand an alias in the command line
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
Expand multiple levels of aliases:
def expand_aliases(self, fn, rest): """Expand multiple levels of aliases: if: alias foo bar /tmp alias baz foo then: baz huhhahhei -> bar /tmp huhhahhei """ line = fn + " " + rest done = set() while 1: pre,_,fn,rest = split_user_input(line, shell_line_split) if fn in self.alias_table: if fn in done: warn("Cyclic alias definition, repeated '%s'" % fn) return "" done.add(fn) l2 = self.transform_alias(fn, rest) if l2 == line: break # ls -> ls -F should not recurse forever if l2.split(None,1)[0] == line.split(None,1)[0]: line = l2 break line=l2 else: break return line
Quote an argument for later parsing by shlex. split ()
def shquote(arg): """Quote an argument for later parsing by shlex.split()""" for c in '"', "'", "\\", "#": if c in arg: return repr(arg) if arg.split()<>[arg]: return repr(arg) return arg
produces rst from nose help
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
Reset graphics attributs to their default values.
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
Yields substrings for which the same escape code applies.
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
Set attributes based on CSI ( Control Sequence Introducer ) code.
def set_csi_code(self, command, params=[]): """ Set attributes based on CSI (Control Sequence Introducer) code. Parameters ---------- command : str The code identifier, i.e. the final character in the sequence. params : sequence of integers, optional The parameter codes for the command. """ if command == 'm': # SGR - Select Graphic Rendition if params: self.set_sgr_code(params) else: self.set_sgr_code([0]) elif (command == 'J' or # ED - Erase Data command == 'K'): # EL - Erase in Line code = params[0] if params else 0 if 0 <= code <= 2: area = 'screen' if command == 'J' else 'line' if code == 0: erase_to = 'end' elif code == 1: erase_to = 'start' elif code == 2: erase_to = 'all' self.actions.append(EraseAction('erase', area, erase_to)) elif (command == 'S' or # SU - Scroll Up command == 'T'): # SD - Scroll Down dir = 'up' if command == 'S' else 'down' count = params[0] if params else 1 self.actions.append(ScrollAction('scroll', dir, 'line', count))
Set attributes based on OSC ( Operating System Command ) parameters.
def set_osc_code(self, params): """ Set attributes based on OSC (Operating System Command) parameters. Parameters ---------- params : sequence of str The parameters for the command. """ try: command = int(params.pop(0)) except (IndexError, ValueError): return if command == 4: # xterm-specific: set color number to color spec. try: color = int(params.pop(0)) spec = params.pop(0) self.color_map[color] = self._parse_xterm_color_spec(spec) except (IndexError, ValueError): pass
Set attributes based on SGR ( Select Graphic Rendition ) codes.
def set_sgr_code(self, params): """ Set attributes based on SGR (Select Graphic Rendition) codes. Parameters ---------- params : sequence of ints A list of SGR codes for one or more SGR commands. Usually this sequence will have one element per command, although certain xterm-specific commands requires multiple elements. """ # Always consume the first parameter. if not params: return code = params.pop(0) if code == 0: self.reset_sgr() elif code == 1: if self.bold_text_enabled: self.bold = True else: self.intensity = 1 elif code == 2: self.intensity = 0 elif code == 3: self.italic = True elif code == 4: self.underline = True elif code == 22: self.intensity = 0 self.bold = False elif code == 23: self.italic = False elif code == 24: self.underline = False elif code >= 30 and code <= 37: self.foreground_color = code - 30 elif code == 38 and params and params.pop(0) == 5: # xterm-specific: 256 color support. if params: self.foreground_color = params.pop(0) elif code == 39: self.foreground_color = None elif code >= 40 and code <= 47: self.background_color = code - 40 elif code == 48 and params and params.pop(0) == 5: # xterm-specific: 256 color support. if params: self.background_color = params.pop(0) elif code == 49: self.background_color = None # Recurse with unconsumed parameters. self.set_sgr_code(params)
Returns a QColor for a given color code or None if one cannot be constructed.
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
Returns a QTextCharFormat that encodes the current style attributes.
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
Given a background color ( a QColor ) attempt to set a color map that will be aesthetically pleasing.
def set_background_color(self, color): """ Given a background color (a QColor), attempt to set a color map that will be aesthetically pleasing. """ # Set a new default color map. self.default_color_map = self.darkbg_color_map.copy() if color.value() >= 127: # Colors appropriate for a terminal with a light background. For # now, only use non-bright colors... for i in xrange(8): self.default_color_map[i + 8] = self.default_color_map[i] # ...and replace white with black. self.default_color_map[7] = self.default_color_map[15] = 'black' # Update the current color map with the new defaults. self.color_map.update(self.default_color_map)
Generate a one - time jwt with an age in seconds
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))
use a thread lock on current method if self. lock is defined
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
Run by housekeeper thread
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]
has this jwt been used?
def already_used(self, tok): """has this jwt been used?""" if tok in self.jwts: return True self.jwts[tok] = time.time() return False
is this token valid?
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
split likely multiline text into lists of strings For file output more friendly to line - based VCS. rejoin_lines ( nb ) will reverse the effects of split_lines ( nb ). Used when writing JSON files.
def split_lines(nb): """split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files. """ for ws in nb.worksheets: for cell in ws.cells: if cell.cell_type == 'code': if 'input' in cell and isinstance(cell.input, basestring): cell.input = cell.input.splitlines() for output in cell.outputs: for key in _multiline_outputs: item = output.get(key, None) if isinstance(item, basestring): output[key] = item.splitlines() else: # text cell for key in ['source', 'rendered']: item = cell.get(key, None) if isinstance(item, basestring): cell[key] = item.splitlines() return nb
Write a notebook to a file like object
def write(self, nb, fp, **kwargs): """Write a notebook to a file like object""" return fp.write(self.writes(nb,**kwargs))
use Semaphore to keep func access thread - safety.
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)
Run the pyglet event loop by processing pending events only.
def inputhook_glut(): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. signal.signal(signal.SIGINT, glut_int_handler) try: t = clock() # Make sure the default window is set after a window has been closed if glut.glutGetWindow() == 0: glut.glutSetWindow( 1 ) glutMainLoopEvent() return 0 while not stdin_ready(): glutMainLoopEvent() # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 5*60.0: # print 'Sleep for 5 s' # dbg time.sleep(5.0) elif used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass return 0
Get common prefix for completions
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)
Reimplemented to ensure a console - like behavior in the underlying text widgets.
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)
Reimplemented to suggest a size that is 80 characters wide and 25 lines high.
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)
Returns whether text can be cut to the clipboard.
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()))
Returns whether text can be pasted from 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
Clear the console.
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
Copy the currently selected text to the clipboard and delete it if it s inside the 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()
Executes source or the input buffer possibly prompting for more input.
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
The text that the user has entered entered at the current prompt.
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')
Sets the text in the input buffer.
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)
Sets the base font for the ConsoleWidget to the specified QFont.
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)
Paste the contents of the clipboard into the input region.
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))
Print the contents of the ConsoleWidget to the specified QPrinter.
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)
Moves the prompt to the top of the viewport.
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)
Sets the font to the default fixed - width font for this platform.
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)
Change the font size by the specified amount ( in points ).
def change_font_size(self, delta): """Change the font size by the specified amount (in points). """ font = self.font size = max(font.pointSize() + delta, 1) # minimum 1 point font.setPointSize(size) self._set_font(font)