INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Generates a Sphinx configuration in `directory`. Parameters ---------- directory : str Base directory to use
def generate_configuration(directory): """ Generates a Sphinx configuration in `directory`. Parameters ---------- directory : str Base directory to use """ # conf.py file for Sphinx conf = osp.join(get_module_source_path('spyder.plugins.help.utils'), 'co...
Update end of line status.
def update_eol(self, os_name): """Update end of line status.""" os_name = to_text_string(os_name) value = {"nt": "CRLF", "posix": "LF"}.get(os_name, "CR") self.set_value(value)
Update encoding of current file.
def update_encoding(self, encoding): """Update encoding of current file.""" value = str(encoding).upper() self.set_value(value)
Update cursor position.
def update_cursor_position(self, line, index): """Update cursor position.""" value = 'Line {}, Col {}'.format(line + 1, index + 1) self.set_value(value)
Update vcs status.
def update_vcs(self, fname, index): """Update vcs status.""" fpath = os.path.dirname(fname) branches, branch, files_modified = get_git_refs(fpath) text = branch if branch else '' if len(files_modified): text = text + ' [{}]'.format(len(files_modified)) self....
Retrieve all Variable Explorer configuration settings. Specifically, return the settings in CONF_SECTION with keys in REMOTE_SETTINGS, and the setting 'dataframe_format'. Returns: dict: settings
def get_settings(self): """ Retrieve all Variable Explorer configuration settings. Specifically, return the settings in CONF_SECTION with keys in REMOTE_SETTINGS, and the setting 'dataframe_format'. Returns: dict: settings """ ...
Change a config option. This function is called if sig_option_changed is received. If the option changed is the dataframe format, then the leading '%' character is stripped (because it can't be stored in the user config). Then, the signal is emitted again, so that the new value is ...
def change_option(self, option_name, new_value): """ Change a config option. This function is called if sig_option_changed is received. If the option changed is the dataframe format, then the leading '%' character is stripped (because it can't be stored in the user config)...
Free memory signal.
def free_memory(self): """Free memory signal.""" self.main.free_memory() QTimer.singleShot(self.INITIAL_FREE_MEMORY_TIME_TRIGGER, lambda: self.main.free_memory()) QTimer.singleShot(self.SECONDARY_FREE_MEMORY_TIME_TRIGGER, lambda: ...
Register shell with variable explorer. This function opens a new NamespaceBrowser for browsing the variables in the shell.
def add_shellwidget(self, shellwidget): """ Register shell with variable explorer. This function opens a new NamespaceBrowser for browsing the variables in the shell. """ shellwidget_id = id(shellwidget) if shellwidget_id not in self.shellwidgets: ...
Import data in current namespace
def import_data(self, fname): """Import data in current namespace""" if self.count(): nsb = self.current_widget() nsb.refresh_table() nsb.import_data(filenames=fname) if self.dockwidget and not self.ismaximized: self.dockwidget.setVi...
Return True if string is valid
def is_valid(self, qstr=None): """Return True if string is valid""" if not self.help.source_is_console(): return True if qstr is None: qstr = self.currentText() if not re.search(r'^[a-zA-Z0-9_\.]*$', str(qstr), 0): return False objtxt = to_text...
Reimplemented to avoid formatting actions
def validate(self, qstr, editing=True): """Reimplemented to avoid formatting actions""" valid = self.is_valid(qstr) if self.hasFocus() and valid is not None: if editing and not valid: # Combo box text is being modified: invalidate the entry self.show_t...
Set font
def set_font(self, font, fixed_font=None): """Set font""" self.webview.set_font(font, fixed_font=fixed_font)
Set font
def set_font(self, font, color_scheme=None): """Set font""" self.editor.set_font(font, color_scheme=color_scheme)
Find tasks in source code (TODO, FIXME, XXX, ...)
def find_tasks(source_code): """Find tasks in source code (TODO, FIXME, XXX, ...)""" results = [] for line, text in enumerate(source_code.splitlines()): for todo in re.findall(TASKS_PATTERN, text): todo_text = (todo[-1].strip(' :').capitalize() if todo[-1] ...
Check source code with pyflakes Returns an empty list if pyflakes is not installed
def check_with_pyflakes(source_code, filename=None): """Check source code with pyflakes Returns an empty list if pyflakes is not installed""" try: if filename is None: filename = '<string>' try: source_code += '\n' except TypeError: # Pyth...
Return checker executable in the form of a list of arguments for subprocess.Popen
def get_checker_executable(name): """Return checker executable in the form of a list of arguments for subprocess.Popen""" if programs.is_program_installed(name): # Checker is properly installed return [name] else: path1 = programs.python_script_exists(package=None, ...
Check source code with checker defined with *args* (list) Returns an empty list if checker is not installed
def check(args, source_code, filename=None, options=None): """Check source code with checker defined with *args* (list) Returns an empty list if checker is not installed""" if args is None: return [] if options is not None: args += options if any(['pyflakes' in arg for arg in ...
Check source code with pycodestyle
def check_with_pep8(source_code, filename=None): """Check source code with pycodestyle""" try: args = get_checker_executable('pycodestyle') results = check(args, source_code, filename=filename, options=['-r']) except Exception: # Never return None to avoid lock in spyder/widget...
Return image inside a QLabel object
def get_image_label(name, default="not_found.png"): """Return image inside a QLabel object""" label = QLabel() label.setPixmap(QPixmap(get_image_path(name, default))) return label
Return QApplication instance Creates it if it doesn't already exist test_time: Time to maintain open the application when testing. It's given in seconds
def qapplication(translate=True, test_time=3): """ Return QApplication instance Creates it if it doesn't already exist test_time: Time to maintain open the application when testing. It's given in seconds """ if running_in_mac_app(): SpyderApplication = MacApplication ...
Select the right file uri scheme according to the operating system
def file_uri(fname): """Select the right file uri scheme according to the operating system""" if os.name == 'nt': # Local file if re.search(r'^[a-zA-Z]:', fname): return 'file:///' + fname # UNC based path else: return 'file://' + fname else: ...
Install Qt translator to the QApplication instance
def install_translator(qapp): """Install Qt translator to the QApplication instance""" global QT_TRANSLATOR if QT_TRANSLATOR is None: qt_translator = QTranslator() if qt_translator.load("qt_"+QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.Translations...
Return keybinding
def keybinding(attr): """Return keybinding""" ks = getattr(QKeySequence, attr) return from_qvariant(QKeySequence.keyBindings(ks)[0], str)
Extract url list from MIME data extlist: for example ('.py', '.pyw')
def mimedata2url(source, extlist=None): """ Extract url list from MIME data extlist: for example ('.py', '.pyw') """ pathlist = [] if source.hasUrls(): for url in source.urls(): path = _process_mime_path(to_text_string(url.toString()), extlist) if path is...
Convert QKeyEvent instance into a tuple
def keyevent2tuple(event): """Convert QKeyEvent instance into a tuple""" return (event.type(), event.key(), event.modifiers(), event.text(), event.isAutoRepeat(), event.count())
Create a QToolButton
def create_toolbutton(parent, text=None, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, autoraise=True, text_beside_icon=False): """Create a QToolButton""" button = QToolButton(parent) if text is not None: button.setText(text) ...
Create a QToolButton directly from a QAction object
def action2button(action, autoraise=True, text_beside_icon=False, parent=None): """Create a QToolButton directly from a QAction object""" if parent is None: parent = action.parent() button = QToolButton(parent) button.setDefaultAction(action) button.setAutoRaise(autoraise) if text...
Enable/disable actions
def toggle_actions(actions, enable): """Enable/disable actions""" if actions is not None: for action in actions: if action is not None: action.setEnabled(enable)
Create a QAction
def create_action(parent, text, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, data=None, menurole=None, context=Qt.WindowShortcut): """Create a QAction""" action = SpyderAction(text, parent) if triggered is not None: action.triggered.conn...
Add the shortcut associated with a given action to its tooltip
def add_shortcut_to_tooltip(action, context, name): """Add the shortcut associated with a given action to its tooltip""" action.setToolTip(action.toolTip() + ' (%s)' % get_shortcut(context=context, name=name))
Add actions to a QMenu or a QToolBar.
def add_actions(target, actions, insert_before=None): """Add actions to a QMenu or a QToolBar.""" previous_action = None target_actions = list(target.actions()) if target_actions: previous_action = target_actions[-1] if previous_action.isSeparator(): previous_action = ...
Create bookmark action
def create_bookmark_action(parent, url, title, icon=None, shortcut=None): """Create bookmark action""" @Slot() def open_url(): return programs.start_file(url) return create_action( parent, title, shortcut=shortcut, icon=icon, triggered=open_url)
Create bookmark actions depending on module installation: bookmarks = ((module_name, url, title), ...)
def create_module_bookmark_actions(parent, bookmarks): """ Create bookmark actions depending on module installation: bookmarks = ((module_name, url, title), ...) """ actions = [] for key, url, title in bookmarks: # Create actions for scientific distros only if Spyder is installed ...
Create action to run a program
def create_program_action(parent, text, name, icon=None, nt_name=None): """Create action to run a program""" if is_text_string(icon): icon = get_icon(icon) if os.name == 'nt' and nt_name is not None: name = nt_name path = programs.find_program(name) if path is not None: ...
Create action to run a GUI based Python script
def create_python_script_action(parent, text, icon, package, module, args=[]): """Create action to run a GUI based Python script""" if is_text_string(icon): icon = get_icon(icon) if programs.python_script_exists(package, module): return create_action(parent, text, icon=icon, ...
Return file type icon
def get_filetype_icon(fname): """Return file type icon""" ext = osp.splitext(fname)[1] if ext.startswith('.'): ext = ext[1:] return get_icon( "%s.png" % ext, ima.icon('FileIcon') )
Show all standard Icons
def show_std_icons(): """ Show all standard Icons """ app = qapplication() dialog = ShowStdIcons(None) dialog.show() sys.exit(app.exec_())
Return a spacing (int) or None if we don't have the appropriate metrics to calculate the spacing. We're trying to adapt the spacing below the tools_layout spacing so that the main_widget has the same vertical position as the editor widgets (which have tabs above). The required spacing is ...
def calc_tools_spacing(tools_layout): """ Return a spacing (int) or None if we don't have the appropriate metrics to calculate the spacing. We're trying to adapt the spacing below the tools_layout spacing so that the main_widget has the same vertical position as the editor widgets (which...
Returns a layout for a set of controls above a main widget. This is a standard layout for many plugin panes (even though, it's currently more often applied not to the pane itself but with in the one widget contained in the pane. tools_layout: a layout containing the top toolbar main_widget: t...
def create_plugin_layout(tools_layout, main_widget=None): """ Returns a layout for a set of controls above a main widget. This is a standard layout for many plugin panes (even though, it's currently more often applied not to the pane itself but with in the one widget contained in the pane. ...
Generic method to show a non-modal dialog and keep reference to the Qt C++ object
def show(self, dialog): """Generic method to show a non-modal dialog and keep reference to the Qt C++ object""" for dlg in list(self.dialogs.values()): if to_text_string(dlg.windowTitle()) \ == to_text_string(dialog.windowTitle()): dlg.show() ...
Add Spyder dependency
def add(modname, features, required_version, installed_version=None, optional=False): """Add Spyder dependency""" global DEPENDENCIES for dependency in DEPENDENCIES: if dependency.modname == modname: raise ValueError("Dependency has already been registered: %s"\ ...
Check if required dependency is installed
def check(modname): """Check if required dependency is installed""" for dependency in DEPENDENCIES: if dependency.modname == modname: return dependency.check() else: raise RuntimeError("Unkwown dependency %s" % modname)
Return a status of dependencies
def status(deps=DEPENDENCIES, linesep=os.linesep): """Return a status of dependencies""" maxwidth = 0 col1 = [] col2 = [] for dependency in deps: title1 = dependency.modname title1 += ' ' + dependency.required_version col1.append(title1) maxwidth = max([maxwi...
Return the status of missing dependencies (if any)
def missing_dependencies(): """Return the status of missing dependencies (if any)""" missing_deps = [] for dependency in DEPENDENCIES: if not dependency.check() and not dependency.optional: missing_deps.append(dependency) if missing_deps: return status(deps=missing_dep...
Check if dependency is installed
def check(self): """Check if dependency is installed""" return programs.is_module_installed(self.modname, self.required_version, self.installed_version)
Return dependency status (string)
def get_installed_version(self): """Return dependency status (string)""" if self.check(): return '%s (%s)' % (self.installed_version, self.OK) else: return '%s (%s)' % (self.installed_version, self.NOK)
Import modules from plugins package and return the list
def get_spyderplugins_mods(io=False): """Import modules from plugins package and return the list""" # Create user directory user_plugin_path = osp.join(get_conf_path(), USER_PLUGIN_DIR) if not osp.isdir(user_plugin_path): os.makedirs(user_plugin_path) modlist, modnames = [], [] ...
Scan the directory `plugin_path` for plugin packages and loads them.
def _get_spyderplugins(plugin_path, is_io, modnames, modlist): """Scan the directory `plugin_path` for plugin packages and loads them.""" if not osp.isdir(plugin_path): return for name in os.listdir(plugin_path): # This is needed in order to register the spyder_io_hdf5 plugin. ...
Import the plugin `module_name` from `plugin_path`, add it to `modlist` and adds its name to `modnames`.
def _import_plugin(module_name, plugin_path, modnames, modlist): """Import the plugin `module_name` from `plugin_path`, add it to `modlist` and adds its name to `modnames`. """ if module_name in modnames: return try: # First add a mock module with the LOCALEPATH attribute so t...
Imports `module_name` from `plugin_path`. Return None if no module is found.
def _import_module_from_path(module_name, plugin_path): """Imports `module_name` from `plugin_path`. Return None if no module is found. """ module = None try: if PY2: info = imp.find_module(module_name, [plugin_path]) if info: module = imp.l...
Get standard platform icon Call 'show_std_icons()' for details
def get_std_icon(name, size=None): """Get standard platform icon Call 'show_std_icons()' for details""" if not name.startswith('SP_'): name = 'SP_' + name icon = QWidget().style().standardIcon(getattr(QStyle, name)) if size is None: return icon else: return QIcon(icon.pix...
Return image inside a QIcon object. default: default image name or icon resample: if True, manually resample icon pixmaps for usual sizes (16, 24, 32, 48, 96, 128, 256). This is recommended for QMainWindow icons created from SVG images on non-Windows platforms due to a Qt bug (see Issue 1314).
def get_icon(name, default=None, resample=False): """Return image inside a QIcon object. default: default image name or icon resample: if True, manually resample icon pixmaps for usual sizes (16, 24, 32, 48, 96, 128, 256). This is recommended for QMainWindow icons created from SVG images on non-Win...
Return the icon depending on the file extension
def get_icon_by_extension(fname, scale_factor): """Return the icon depending on the file extension""" application_icons = {} application_icons.update(BIN_FILES) application_icons.update(DOCUMENT_FILES) if osp.isdir(fname): return icon('DirOpenIcon', scale_factor) else: basename =...
Update `show_errors` and hide dialog box. Overrides method of `QDialogBox`.
def accept(self): """ Update `show_errors` and hide dialog box. Overrides method of `QDialogBox`. """ AutosaveErrorDialog.show_errors = not self.dismiss_box.isChecked() return QDialog.accept(self)
Setup context menu common actions
def setup_common_actions(self): """Setup context menu common actions""" self.collapse_all_action = create_action(self, text=_('Collapse all'), icon=ima.icon('collapse'), triggered=self.col...
Returns a list of menu actions
def get_menu_actions(self): """Returns a list of menu actions""" items = self.selectedItems() actions = self.get_actions_from_items(items) if actions: actions.append(None) actions += self.common_actions return actions
Item selection has changed
def item_selection_changed(self): """Item selection has changed""" is_selection = len(self.selectedItems()) > 0 self.expand_selection_action.setEnabled(is_selection) self.collapse_selection_action.setEnabled(is_selection)
Return items (excluding top level items)
def get_items(self): """Return items (excluding top level items)""" itemlist = [] def add_to_itemlist(item): for index in range(item.childCount()): citem = item.child(index) itemlist.append(citem) add_to_itemlist(citem) ...
Save all items expanded state
def save_expanded_state(self): """Save all items expanded state""" self.__expanded_state = {} def add_to_state(item): user_text = get_item_user_text(item) self.__expanded_state[hash(user_text)] = item.isExpanded() def browse_children(item): add_...
Restore all items expanded state
def restore_expanded_state(self): """Restore all items expanded state""" if self.__expanded_state is None: return for item in self.get_items()+self.get_top_level_items(): user_text = get_item_user_text(item) is_expanded = self.__expanded_state.get(hash(u...
Sorting tree wrt top level items
def sort_top_level_items(self, key): """Sorting tree wrt top level items""" self.save_expanded_state() items = sorted([self.takeTopLevelItem(0) for index in range(self.topLevelItemCount())], key=key) for index, item in enumerate(items): self.inse...
Override Qt method
def contextMenuEvent(self, event): """Override Qt method""" self.update_menu() self.menu.popup(event.globalPos())
Returns a list containing the names of all the modules available in the standard library. Based on the function get_root_modules from the IPython project. Present in IPython.core.completerlib in v0.13.1 Copyright (C) 2010-2011 The IPython Development Team. Distributed under the terms of th...
def get_stdlib_modules(): """ Returns a list containing the names of all the modules available in the standard library. Based on the function get_root_modules from the IPython project. Present in IPython.core.completerlib in v0.13.1 Copyright (C) 2010-2011 The IPython Development Team....
Prints the editor fold tree to stdout, for debugging purpose. :param editor: CodeEditor instance. :param file: file handle where the tree will be printed. Default is stdout. :param print_blocks: True to print all blocks, False to only print blocks that are fold triggers
def print_tree(editor, file=sys.stdout, print_blocks=False, return_list=False): """ Prints the editor fold tree to stdout, for debugging purpose. :param editor: CodeEditor instance. :param file: file handle where the tree will be printed. Default is stdout. :param print_blocks: True to print all bl...
Dict --> Dict of lists
def envdict2listdict(envdict): """Dict --> Dict of lists""" sep = os.path.pathsep for key in envdict: if sep in envdict[key]: envdict[key] = [path.strip() for path in envdict[key].split(sep)] return envdict
Dict of lists --> Dict
def listdict2envdict(listdict): """Dict of lists --> Dict""" for key in listdict: if isinstance(listdict[key], list): listdict[key] = os.path.pathsep.join(listdict[key]) return listdict
Run Windows environment variable editor
def main(): """Run Windows environment variable editor""" from spyder.utils.qthelpers import qapplication app = qapplication() if os.name == 'nt': dialog = WinUserEnvDialog() else: dialog = EnvDialog() dialog.show() app.exec_()
Qt override.
def keyPressEvent(self, event): """ Qt override. """ if event.key() in [Qt.Key_Enter, Qt.Key_Return]: self._parent.process_text() if self._parent.is_valid(): self._parent.keyPressEvent(event) else: QLineEdit.keyPressEve...
Qt override. This is needed to be able to intercept the Tab key press event.
def event(self, event): """ Qt override. This is needed to be able to intercept the Tab key press event. """ if event.type() == QEvent.KeyPress: if (event.key() == Qt.Key_Tab or event.key() == Qt.Key_Space): text = self.text() ...
Qt override.
def keyPressEvent(self, event): """ Qt override. """ if event.key() in [Qt.Key_Enter, Qt.Key_Return]: QTableWidget.keyPressEvent(self, event) # To avoid having to enter one final tab self.setDisabled(True) self.setDisabled(False) ...
Update the column and row numbering in the headers.
def reset_headers(self): """ Update the column and row numbering in the headers. """ rows = self.rowCount() cols = self.columnCount() for r in range(rows): self.setVerticalHeaderItem(r, QTableWidgetItem(str(r))) for c in range(cols): ...
Return the entered array in a parseable form.
def text(self): """ Return the entered array in a parseable form. """ text = [] rows = self.rowCount() cols = self.columnCount() # handle empty table case if rows == 2 and cols == 2: item = self.item(0, 0) if item is Non...
Qt override.
def keyPressEvent(self, event): """ Qt override. """ QToolTip.hideText() ctrl = event.modifiers() & Qt.ControlModifier if event.key() in [Qt.Key_Enter, Qt.Key_Return]: if ctrl: self.process_text(array=False) else: ...
Qt Override. Usefull when in line edit mode.
def event(self, event): """ Qt Override. Usefull when in line edit mode. """ if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab: return False return QWidget.event(self, event)
Construct the text based on the entered content in the widget.
def process_text(self, array=True): """ Construct the text based on the entered content in the widget. """ if array: prefix = 'np.array([[' else: prefix = 'np.matrix([[' suffix = ']])' values = self._widget.text().strip() ...
Updates the icon and tip based on the validity of the array content.
def update_warning(self): """ Updates the icon and tip based on the validity of the array content. """ widget = self._button_warning if not self.is_valid(): tip = _('Array dimensions not valid') widget.setIcon(ima.icon('MessageBoxWarning')) ...
Get selected language setting and save to language configuration file.
def _save_lang(self): """ Get selected language setting and save to language configuration file. """ for combobox, (option, _default) in list(self.comboboxes.items()): if option == 'interface_language': data = combobox.itemData(combobox.currentIndex()) ...
Check if path has write access
def is_writable(path): """Check if path has write access""" try: testfile = tempfile.TemporaryFile(dir=path) testfile.close() except OSError as e: if e.errno == errno.EACCES: # 13 return False return True
Get all available project types.
def _get_project_types(self): """Get all available project types.""" project_types = get_available_project_types() projects = [] for project in project_types: projects.append(project.PROJECT_TYPE_NAME) return projects
Select directory.
def select_location(self): """Select directory.""" location = osp.normpath(getexistingdirectory(self, _("Select directory"), self.location)) if location: if is_writable(l...
Update text of location.
def update_location(self, text=''): """Update text of location.""" self.text_project_name.setEnabled(self.radio_new_dir.isChecked()) name = self.text_project_name.text().strip() if name and self.radio_new_dir.isChecked(): path = osp.join(self.location, name) ...
Create project.
def create_project(self): """Create project.""" packages = ['python={0}'.format(self.combo_python_version.currentText())] self.sig_project_creation_requested.emit( self.text_location.text(), self.combo_project_type.currentText(), packages) self....
Set shell styles font
def set_font(self, font): """Set shell styles font""" self.setFont(font) self.set_pythonshell_font(font) cursor = self.textCursor() cursor.select(QTextCursor.Document) charformat = QTextCharFormat() charformat.setFontFamily(font.family()) charforma...
Setup shell context menu
def setup_context_menu(self): """Setup shell context menu""" self.menu = QMenu(self) self.cut_action = create_action(self, _("Cut"), shortcut=keybinding('Cut'), icon=ima.icon('editcut'), ...
Reimplement Qt method
def contextMenuEvent(self, event): """Reimplement Qt method""" state = self.has_selected_text() self.copy_action.setEnabled(state) self.cut_action.setEnabled(state) self.delete_action.setEnabled(state) self.menu.popup(event.globalPos()) event.accept()
Select current line (without selecting console prompt)
def _select_input(self): """Select current line (without selecting console prompt)""" line, index = self.get_position('eof') if self.current_prompt_pos is None: pline, pindex = line, index else: pline, pindex = self.current_prompt_pos self.setSelect...
Set input buffer
def _set_input_buffer(self, text): """Set input buffer""" if self.current_prompt_pos is not None: self.replace_text(self.current_prompt_pos, 'eol', text) else: self.insert(text) self.set_cursor_position('eof')
Return input buffer
def _get_input_buffer(self): """Return input buffer""" input_buffer = '' if self.current_prompt_pos is not None: input_buffer = self.get_text(self.current_prompt_pos, 'eol') input_buffer = input_buffer.replace(os.linesep, '\n') return input_buffer
Print a new prompt and save its (line, index) position
def new_prompt(self, prompt): """ Print a new prompt and save its (line, index) position """ if self.get_cursor_line_column()[1] != 0: self.write('\n') self.write(prompt, prompt=True) # now we update our cursor giving end of prompt self.current...
Check if selected text is r/w, otherwise remove read-only parts of selection
def check_selection(self): """ Check if selected text is r/w, otherwise remove read-only parts of selection """ if self.current_prompt_pos is None: self.set_cursor_position('eof') else: self.truncate_selection(self.current_prompt_pos)
Copy text to clipboard... or keyboard interrupt
def copy(self): """Copy text to clipboard... or keyboard interrupt""" if self.has_selected_text(): ConsoleBaseWidget.copy(self) elif not sys.platform == 'darwin': self.interrupt()
Save current history log (all text in console)
def save_historylog(self): """Save current history log (all text in console)""" title = _("Save history log") self.redirect_stdio.emit(False) filename, _selfilter = getsavefilename(self, title, self.historylog_filename, "%s (*.log)" % _("History logs")) ...
On new input line
def on_new_line(self): """On new input line""" self.set_cursor_position('eof') self.current_prompt_pos = self.get_position('cursor') self.new_input_line = False
Pre-process keypress event: return True if event is accepted, false otherwise
def preprocess_keyevent(self, event): """Pre-process keypress event: return True if event is accepted, false otherwise""" # Copy must be done first to be able to copy read-only text parts # (otherwise, right below, we would remove selection # if not on current line) ...
Post-process keypress event: in InternalShell, this is method is called when shell is ready
def postprocess_keyevent(self, event): """Post-process keypress event: in InternalShell, this is method is called when shell is ready""" event, text, key, ctrl, shift = restore_keyevent(event) # Is cursor on the last line? and after prompt? if len(text): ...
Load history from a .py file in user home directory
def load_history(self): """Load history from a .py file in user home directory""" if osp.isfile(self.history_filename): rawhistory, _ = encoding.readlines(self.history_filename) rawhistory = [line.replace('\n', '') for line in rawhistory] if rawhistory[1] != self...
Simulate stderr
def write_error(self, text): """Simulate stderr""" self.flush() self.write(text, flush=True, error=True) if get_debug_level(): STDERR.write(text)
Simulate stdout and stderr
def write(self, text, flush=False, error=False, prompt=False): """Simulate stdout and stderr""" if prompt: self.flush() if not is_string(text): # This test is useful to discriminate QStrings from decoded str text = to_text_string(text) self.__bu...
Flush buffer, write text to console
def flush(self, error=False, prompt=False): """Flush buffer, write text to console""" # Fix for Issue 2452 if PY3: try: text = "".join(self.__buffer) except TypeError: text = b"".join(self.__buffer) try: ...