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...
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 ZeroDiv...
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. ...
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 suppo...
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 ...
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) ...
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) ...
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) ...
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._p...
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...
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 ...
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 re...
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...
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 handle...
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...
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...
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 multipl...
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: ...
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_...
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 b...
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...
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...
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.""...
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 callabl...
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. ...
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 = '%sg...
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...
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_p...
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 w...
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 ke...
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...
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}" % maxlin...
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() sea...
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 th...
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 o...
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...
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 ...
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, loca...
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. ...
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 th...
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)...
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 =...
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-glob...
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...
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(Vie...
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 ca...
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(...
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: ...
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++.ex...
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...
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.us...
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,...
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...
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,...
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 c...
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 ...
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.setForegrou...
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: ...
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: ...
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.Decod...
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: ...
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) retur...
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 ...
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.co...
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() i...
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....
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() els...
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 ...
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...
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 tex...
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.documen...
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 ...
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_...
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) s...
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 ...
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)