text
stringlengths
81
112k
Return True if module *module_name* is installed If version is not None, checking module version (module must have an attribute named '__version__') version may starts with =, >=, > or < to specify the exact requirement ; multiple conditions may be separated by ';' (e.g. '>=0.13;<1.0') in...
Check that the python interpreter file has a valid name. def is_python_interpreter_valid_name(filename): """Check that the python interpreter file has a valid name.""" pattern = r'.*python(\d\.?\d*)?(w)?(.exe)?$' if re.match(pattern, filename, flags=re.I) is None: return False else: ...
Evaluate wether a file is a python interpreter or not. def is_python_interpreter(filename): """Evaluate wether a file is a python interpreter or not.""" real_filename = os.path.realpath(filename) # To follow symlink if existent if (not osp.isfile(real_filename) or not is_python_interpreter_va...
Check that the python interpreter has 'pythonw'. def is_pythonw(filename): """Check that the python interpreter has 'pythonw'.""" pattern = r'.*python(\d\.?\d*)?w(.exe)?$' if re.match(pattern, filename, flags=re.I) is None: return False else: return True
Check that the python interpreter can execute help. def check_python_help(filename): """Check that the python interpreter can execute help.""" try: proc = run_program(filename, ["-h"]) output = to_text_string(proc.communicate()[0]) valid = ("Options and arguments (and corresponding...
Override Qt method. Returns the widget size hint (based on the editor font size). def sizeHint(self): """Override Qt method. Returns the widget size hint (based on the editor font size). """ fm = QFontMetrics(self.editor.font()) size_hint = QSize(fm.height(), fm.height...
Draw the given breakpoint pixmap. Args: top (int): top of the line to draw the breakpoint icon. painter (QPainter) icon_name (srt): key of icon to draw (see: self.icons) def _draw_breakpoint_icon(self, top, painter, icon_name): """Draw the given breakpoint pixmap. ...
Override Qt method. Paint breakpoints icons. def paintEvent(self, event): """Override Qt method. Paint breakpoints icons. """ super(DebuggerPanel, self).paintEvent(event) painter = QPainter(self) painter.fillRect(event.rect(), self.editor.sideareas_color) ...
Override Qt method Add/remove breakpoints by single click. def mousePressEvent(self, event): """Override Qt method Add/remove breakpoints by single click. """ line_number = self.editor.get_linenumber_from_mouse_event(event) shift = event.modifiers() & Qt.ShiftModifier ...
Override Qt method. Draw semitransparent breakpoint hint. def mouseMoveEvent(self, event): """Override Qt method. Draw semitransparent breakpoint hint. """ self.line_number_hint = self.editor.get_linenumber_from_mouse_event( event) self.update()
Change visibility and connect/disconnect signal. Args: state (bool): Activate/deactivate. def on_state_changed(self, state): """Change visibility and connect/disconnect signal. Args: state (bool): Activate/deactivate. """ if state: self.edit...
Qt/Python2/3 compatibility helper. def handle_qbytearray(obj, encoding): """Qt/Python2/3 compatibility helper.""" if isinstance(obj, QByteArray): obj = obj.data() return to_text_string(obj, encoding=encoding)
This methods illustrates how the workers can be used. def sleeping_func(arg, secs=10, result_queue=None): """This methods illustrates how the workers can be used.""" import time time.sleep(secs) if result_queue is not None: result_queue.put(arg) else: return arg
Start the worker (emits sig_started signal with worker as arg). def start(self): """Start the worker (emits sig_started signal with worker as arg).""" if not self._started: self.sig_started.emit(self) self._started = True
Start process worker for given method args and kwargs. def _start(self): """Start process worker for given method args and kwargs.""" error = None output = None try: output = self.func(*self.args, **self.kwargs) except Exception as err: error = err ...
Return the encoding/codepage to use. def _get_encoding(self): """Return the encoding/codepage to use.""" enco = 'utf-8' # Currently only cp1252 is allowed? if WIN: import ctypes codepage = to_text_string(ctypes.cdll.kernel32.GetACP()) # import local...
Set the environment on the QProcess. def _set_environment(self, environ): """Set the environment on the QProcess.""" if environ: q_environ = self._process.processEnvironment() for k, v in environ.items(): q_environ.insert(k, v) self._process.setProces...
Callback for partial output. def _partial(self): """Callback for partial output.""" raw_stdout = self._process.readAllStandardOutput() stdout = handle_qbytearray(raw_stdout, self._get_encoding()) if self._partial_stdout is None: self._partial_stdout = stdout else: ...
Callback for communicate. def _communicate(self): """Callback for communicate.""" if (not self._communicate_first and self._process.state() == QProcess.NotRunning): self.communicate() elif self._fired: self._timer.stop()
Retrieve information. def communicate(self): """Retrieve information.""" self._communicate_first = True self._process.waitForFinished() enco = self._get_encoding() if self._partial_stdout is None: raw_stdout = self._process.readAllStandardOutput() stdout...
Start process. def _start(self): """Start process.""" if not self._fired: self._partial_ouput = None self._process.start(self._cmd_list[0], self._cmd_list[1:]) self._timer.start()
Terminate running processes. def terminate(self): """Terminate running processes.""" if self._process.state() == QProcess.Running: try: self._process.terminate() except Exception: pass self._fired = True
Delete periodically workers in workers bag. def _clean_workers(self): """Delete periodically workers in workers bag.""" while self._bag_collector: self._bag_collector.popleft() self._timer_worker_delete.stop()
Start threads and check for inactive workers. def _start(self, worker=None): """Start threads and check for inactive workers.""" if worker: self._queue_workers.append(worker) if self._queue_workers and self._running_threads < self._max_threads: #print('Queue: {0} Runnin...
Create a new python worker instance. def create_python_worker(self, func, *args, **kwargs): """Create a new python worker instance.""" worker = PythonWorker(func, args, kwargs) self._create_worker(worker) return worker
Create a new process worker instance. def create_process_worker(self, cmd_list, environ=None): """Create a new process worker instance.""" worker = ProcessWorker(cmd_list, environ=environ) self._create_worker(worker) return worker
Terminate all worker processes. def terminate_all(self): """Terminate all worker processes.""" for worker in self._workers: worker.terminate() # for thread in self._threads: # try: # thread.terminate() # thread.wait() # except...
Common worker setup. def _create_worker(self, worker): """Common worker setup.""" worker.sig_started.connect(self._start) self._workers.append(worker)
Gather data about a given file. Returns a dict with fields name, mtime and size, containing the relevant data for the fiel. def gather_file_data(name): """ Gather data about a given file. Returns a dict with fields name, mtime and size, containing the relevant data for the fiel. """ r...
Convert file data to a string for display. This function takes the file data produced by gather_file_data(). def file_data_to_str(data): """ Convert file data to a string for display. This function takes the file data produced by gather_file_data(). """ if not data: return _('<i>File ...
Make temporary files to simulate a recovery use case. Create a directory under tempdir containing some original files and another directory with autosave files. Return a tuple with the name of the directory with the original files, the name of the directory with the autosave files, and the autosave map...
Gather data about files which may be recovered. The data is stored in self.data as a list of tuples with the data pertaining to the original file and the autosave file. Each element of the tuple is a dict as returned by gather_file_data(). def gather_data(self): """ Gather data...
Add label with explanation at top of dialog window. def add_label(self): """Add label with explanation at top of dialog window.""" txt = _('Autosave files found. What would you like to do?\n\n' 'This dialog will be shown again on next startup if any ' 'autosave files are...
Add a label to specified cell in table. def add_label_to_table(self, row, col, txt): """Add a label to specified cell in table.""" label = QLabel(txt) label.setMargin(5) label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.table.setCellWidget(row, col, label)
Add table with info about files to be recovered. def add_table(self): """Add table with info about files to be recovered.""" table = QTableWidget(len(self.data), 3, self) self.table = table labels = [_('Original file'), _('Autosave file'), _('Actions')] table.setHorizontalHeade...
Add a cancel button at the bottom of the dialog window. def add_cancel_button(self): """Add a cancel button at the bottom of the dialog window.""" button_box = QDialogButtonBox(QDialogButtonBox.Cancel, self) button_box.rejected.connect(self.reject) self.layout.addWidget(button_box)
Register plugin in Spyder's main window def register_plugin(self): """Register plugin in Spyder's main window""" self.redirect_stdio.connect(self.main.redirect_internalshell_stdio) self.main.console.shell.refresh.connect(self.refresh_plugin) iconsize = 24 self.toolbar.setI...
Refresh widget def refresh_plugin(self): """Refresh widget""" curdir = getcwd_or_home() self.pathedit.add_text(curdir) self.save_wdhistory() self.set_previous_enabled.emit( self.histindex is not None and self.histindex > 0) self.set_ne...
Load history from a text file in user home directory def load_wdhistory(self, workdir=None): """Load history from a text file in user home directory""" if osp.isfile(self.LOG_PATH): wdhistory, _ = encoding.readlines(self.LOG_PATH) wdhistory = [name for name in wdhistory if o...
Save history to a text file in user home directory def save_wdhistory(self): """Save history to a text file in user home directory""" text = [ to_text_string( self.pathedit.itemText(index) ) \ for index in range(self.pathedit.count()) ] try: encoding.writelines...
Select directory def select_directory(self): """Select directory""" self.redirect_stdio.emit(False) directory = getexistingdirectory(self.main, _("Select directory"), getcwd_or_home()) if directory: self.chdir(directory) ...
Change working directory to parent directory def parent_directory(self): """Change working directory to parent directory""" self.chdir(os.path.join(getcwd_or_home(), os.path.pardir))
Set directory as working directory def chdir(self, directory, browsing_history=False, refresh_explorer=True, refresh_console=True): """Set directory as working directory""" if directory: directory = osp.abspath(to_text_string(directory)) # Working directory hist...
Add/remove breakpoint. def toogle_breakpoint(self, line_number=None, condition=None, edit_condition=False): """Add/remove breakpoint.""" if not self.editor.is_python_like(): return if line_number is None: block = self.editor.textCursor().block()...
Get breakpoints def get_breakpoints(self): """Get breakpoints""" breakpoints = [] block = self.editor.document().firstBlock() for line_number in range(1, self.editor.document().blockCount()+1): data = block.userData() if data and data.breakpoint: ...
Clear breakpoints def clear_breakpoints(self): """Clear breakpoints""" self.breakpoints = [] for data in self.editor.blockuserdata_list[:]: data.breakpoint = False # data.breakpoint_condition = None # not necessary, but logical if data.is_empty(): ...
Set breakpoints def set_breakpoints(self, breakpoints): """Set breakpoints""" self.clear_breakpoints() for line_number, condition in breakpoints: self.toogle_breakpoint(line_number, condition) self.breakpoints = self.get_breakpoints()
Breakpoint list has changed def breakpoints_changed(self): """Breakpoint list has changed""" breakpoints = self.get_breakpoints() if self.breakpoints != breakpoints: self.breakpoints = breakpoints self.save_breakpoints()
Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Take from the IPython project (in IPython/core/completer.py in v0.13) Spyder team: Add some changes to deal with escaped quotes - Copyright (C) 2008-2011 IPython...
Connect/disconnect sig_key_pressed signal. def on_state_changed(self, state): """Connect/disconnect sig_key_pressed signal.""" if state: self.editor.sig_key_pressed.connect(self._on_key_pressed) else: self.editor.sig_key_pressed.disconnect(self._on_key_pressed)
Control how to automatically insert quotes in various situations. def _autoinsert_quotes(self, key): """Control how to automatically insert quotes in various situations.""" char = {Qt.Key_QuoteDbl: '"', Qt.Key_Apostrophe: '\''}[key] line_text = self.editor.get_text('sol', 'eol') line_t...
Populate the given ``combobox`` with the class or function names. Parameters ---------- combobox : :class:`qtpy.QtWidets.QComboBox` The combobox to populate data : list of :class:`FoldScopeHelper` The data to populate with. There should be one list element per class or function ...
Return a list of all the class/function definition ranges. Parameters ---------- editor : :class:`spyder.plugins.editor.widgets.codeeditor.CodeEditor` Returns ------- folds : list of :class:`FoldScopeHelper` A list of all the class or function defintion fold points. def _get_fold_leve...
Adjust the parent stack in-place as the trigger level changes. Parameters ---------- fsh : :class:`FoldScopeHelper` The :class:`FoldScopeHelper` object to act on. prev : :class:`FoldScopeHelper` The previous :class:`FoldScopeHelper` object. parents : list of :class:`FoldScopeHelper`...
Split out classes and methods into two separate lists. Parameters ---------- folds : list of :class:`FoldScopeHelper` The result of :func:`_get_fold_levels`. Returns ------- classes, functions: list of :class:`FoldScopeHelper` Two separate lists of :class:`FoldScopeHelper` obje...
Get the parents at a given linenum. If parents is empty, then the linenum belongs to the module. Parameters ---------- folds : list of :class:`FoldScopeHelper` linenum : int The line number to get parents for. Typically this would be the cursor position. Returns ------- ...
Update the combobox with the selected item based on the parents. Parameters ---------- parents : list of :class:`FoldScopeHelper` combobox : :class:`qtpy.QtWidets.QComboBox` The combobox to populate Returns ------- None def update_selected_cb(parents, combobox): """ Update...
Update the internal data values. def _update_data(self): """Update the internal data values.""" _old = self.folds self.folds = _get_fold_levels(self.editor) # only update our dropdown lists if the folds have changed. if self.folds != _old: self.classes, self.funcs =...
Move the cursor to the selected definition. def combobox_activated(self): """Move the cursor to the selected definition.""" sender = self.sender() data = sender.itemData(sender.currentIndex()) if isinstance(data, FoldScopeHelper): self.editor.go_to_line(data.line + 1)
Updates the dropdowns to reflect the current class and function. def update_selected(self, linenum): """Updates the dropdowns to reflect the current class and function.""" self.parents = _get_parents(self.funcs, linenum) update_selected_cb(self.parents, self.method_cb) self.parents = _...
Set text editor palette colors: background color and caret (text cursor) color def set_palette(self, background, foreground): """ Set text editor palette colors: background color and caret (text cursor) color """ palette = QPalette() palette.setColor(QPale...
Set extra selections for a key. Also assign draw orders to leave current_cell and current_line in the backgrund (and avoid them to cover other decorations) NOTE: This will remove previous decorations added to the same key. Args: key (str) name of the extra selecti...
Add extra selections to DecorationsManager. TODO: This method could be remove it and decorations could be added/removed in set_extra_selections/clear_extra_selections. def update_extra_selections(self): """Add extra selections to DecorationsManager. TODO: This method could be re...
Remove decorations added through set_extra_selections. Args: key (str) name of the extra selections group. def clear_extra_selections(self, key): """Remove decorations added through set_extra_selections. Args: key (str) name of the extra selections group. ...
Highlight current line def highlight_current_line(self): """Highlight current line""" selection = TextDecoration(self.textCursor()) selection.format.setProperty(QTextFormat.FullWidthSelection, to_qvariant(True)) selection.format.setBackground(se...
Highlight current cell def highlight_current_cell(self): """Highlight current cell""" if self.cell_separators is None or \ not self.highlight_current_cell_enabled: return cursor, whole_file_selected, whole_screen_selected =\ self.select_current_cell_in_vi...
Brace matching def cursor_position_changed(self): """Brace matching""" if self.bracepos is not None: self.__highlight(self.bracepos, cancel=True) self.bracepos = None cursor = self.textCursor() if cursor.position() == 0: return cursor....
Set wrap mode Valid *mode* values: None, 'word', 'character' def set_wrap_mode(self, mode=None): """ Set wrap mode Valid *mode* values: None, 'word', 'character' """ if mode == 'word': wrap_mode = QTextOption.WrapAtWordBoundaryOrAnywhere elif ...
Reimplement Qt method Fix PyQt4 bug on Windows and Python 3 def toPlainText(self): """ Reimplement Qt method Fix PyQt4 bug on Windows and Python 3 """ # Fix what appears to be a PyQt4 bug when getting file # contents under Windows and PY3. This bug leads t...
Return selected text as a processed text, to be executable in a Python/IPython interpreter def get_selection_as_executable_code(self): """Return selected text as a processed text, to be executable in a Python/IPython interpreter""" ls = self.get_line_separator() _indent =...
Return True if cursor (or text block) is on a block separator def is_cell_separator(self, cursor=None, block=None): """Return True if cursor (or text block) is on a block separator""" assert cursor is not None or block is not None if cursor is not None: cursor0 = QTextCursor(cur...
Select cell under cursor cell = group of lines separated by CELL_SEPARATORS returns the textCursor and a boolean indicating if the entire file is selected def select_current_cell(self): """Select cell under cursor cell = group of lines separated by CELL_SEPARATORS ...
Select cell under cursor in the visible portion of the file cell = group of lines separated by CELL_SEPARATORS returns -the textCursor -a boolean indicating if the entire file is selected -a boolean indicating if the entire visible portion of the file is selected def sel...
Go to the next cell of lines def go_to_next_cell(self): """Go to the next cell of lines""" cursor = self.textCursor() cursor.movePosition(QTextCursor.NextBlock) cur_pos = prev_pos = cursor.position() while not self.is_cell_separator(cursor): # Moving to the nex...
Go to the previous cell of lines def go_to_previous_cell(self): """Go to the previous cell of lines""" cursor = self.textCursor() cur_pos = prev_pos = cursor.position() if self.is_cell_separator(cursor): # Move to the previous cell cursor.movePosition(QTe...
Restore cursor selection from position bounds def __restore_selection(self, start_pos, end_pos): """Restore cursor selection from position bounds""" cursor = self.textCursor() cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) self.setTextCurs...
Duplicate current line or selected text def __duplicate_line_or_selection(self, after_current_line=True): """Duplicate current line or selected text""" cursor = self.textCursor() cursor.beginEditBlock() start_pos, end_pos = self.__save_selection() if to_text_string(cursor.s...
Move current line or selected text def __move_line_or_selection(self, after_current_line=True): """Move current line or selected text""" cursor = self.textCursor() cursor.beginEditBlock() start_pos, end_pos = self.__save_selection() last_line = False # ------ Sel...
Go to the end of the current line and create a new line def go_to_new_line(self): """Go to the end of the current line and create a new line""" self.stdkey_end(False, False) self.insert_text(self.get_line_separator())
Extend current selection to complete lines def extend_selection_to_complete_lines(self): """Extend current selection to complete lines""" cursor = self.textCursor() start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd() cursor.setPosition(start_pos) cursor.setP...
Delete current line def delete_line(self): """Delete current line""" cursor = self.textCursor() if self.has_selected_text(): self.extend_selection_to_complete_lines() start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd() cursor.setPosition...
Unselect read-only parts in shell, like prompt def truncate_selection(self, position_from): """Unselect read-only parts in shell, like prompt""" position_from = self.get_position(position_from) cursor = self.textCursor() start, end = cursor.selectionStart(), cursor.selectionEnd() ...
In shell, avoid editing text except between prompt and EOF def restrict_cursor_position(self, position_from, position_to): """In shell, avoid editing text except between prompt and EOF""" position_from = self.get_position(position_from) position_to = self.get_position(position_to) c...
Hide calltip when necessary def hide_tooltip_if_necessary(self, key): """Hide calltip when necessary""" try: calltip_char = self.get_character(self.calltip_position) before = self.is_cursor_before(self.calltip_position, char_offset...
Smart HOME feature: cursor is first moved at indentation position, then at the start of the line def stdkey_home(self, shift, ctrl, prompt_pos=None): """Smart HOME feature: cursor is first moved at indentation position, then at the start of the line""" move_mode = self.__get_move_mo...
Reimplement Qt method def mousePressEvent(self, event): """Reimplement Qt method""" if sys.platform.startswith('linux') and event.button() == Qt.MidButton: self.calltip_widget.hide() self.setFocus() event = QMouseEvent(QEvent.MouseButtonPress, event.pos(), ...
Reimplemented to handle focus def focusInEvent(self, event): """Reimplemented to handle focus""" self.focus_changed.emit() self.focus_in.emit() self.highlight_current_cell() QPlainTextEdit.focusInEvent(self, event)
Reimplemented to handle focus def focusOutEvent(self, event): """Reimplemented to handle focus""" self.focus_changed.emit() QPlainTextEdit.focusOutEvent(self, event)
Reimplemented to emit zoom in/out signals when Ctrl is pressed def wheelEvent(self, event): """Reimplemented to emit zoom in/out signals when Ctrl is pressed""" # This feature is disabled on MacOS, see Issue 1510 if sys.platform != 'darwin': if event.modifiers() & Qt.ControlModi...
Convert options into commands return commands, message def get_options(argv=None): """ Convert options into commands return commands, message """ parser = argparse.ArgumentParser(usage="spyder [options] files") parser.add_argument('--new-instance', action='store_true', default=False, ...
Set a list of files opened by the project. def set_recent_files(self, recent_files): """Set a list of files opened by the project.""" for recent_file in recent_files[:]: if not os.path.isfile(recent_file): recent_files.remove(recent_file) try: self....
Return a list of files opened by the project. def get_recent_files(self): """Return a list of files opened by the project.""" try: recent_files = self.CONF[WORKSPACE].get('main', 'recent_files', default=[]) except EnvironmentE...
Set project root path. def set_root_path(self, root_path): """Set project root path.""" if self.name is None: self.name = osp.basename(root_path) self.root_path = to_text_string(root_path) config_path = self.__get_project_config_path() if osp.exists(config_path...
Rename project and rename its root path accordingly. def rename(self, new_name): """Rename project and rename its root path accordingly.""" old_name = self.name self.name = new_name pypath = self.relative_pythonpath # ?? self.root_path = self.root_path[:-len(old_name)]+new...
Start pydoc server def initialize(self): """Start pydoc server""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() self.start_server()
Start pydoc server def start_server(self): """Start pydoc server""" if self.server is None: self.port = select_port(default_port=self.DEFAULT_PORT) self.set_home_url('http://localhost:%d/' % self.port) elif self.server.isRunning(): self.server.server_st...
Convert text address into QUrl object def text_to_url(self, text): """Convert text address into QUrl object""" if text.startswith('/'): text = text[1:] return QUrl(self.home_url.toString()+text+'.html')
Instruct current editorstack to autosave files where necessary. def do_autosave(self): """Instruct current editorstack to autosave files where necessary.""" logger.debug('Autosave triggered') stack = self.editor.get_current_editorstack() stack.autosave.autosave_all() self.start_...
Offer to recover files from autosave. def try_recover_from_autosave(self): """Offer to recover files from autosave.""" autosave_dir = get_conf_path('autosave') autosave_mapping = CONF.get('editor', 'autosave_mapping', {}) dialog = RecoveryDialog(autosave_dir, autosave_mapping, ...
Create unique autosave file name for specified file name. Args: filename (str): original file name autosave_dir (str): directory in which autosave files are stored def create_unique_autosave_filename(self, filename, autosave_dir): """ Create unique autosave file name fo...