text
stringlengths
81
112k
Setup logging with cli options defined by the user. def setup_logging(cli_options): """Setup logging with cli options defined by the user.""" if cli_options.debug_info or get_debug_level() > 0: levels = {2: logging.INFO, 3: logging.DEBUG} log_level = levels[get_debug_level()] log_f...
Qt warning messages are intercepted by this handler. On some operating systems, warning messages might be displayed even if the actual message does not apply. This filter adds a blacklist for messages that are being printed for no apparent reason. Anything else will get printed in the internal con...
Initialize Qt, patching sys.exit and eventually setting up ETS def initialize(): """Initialize Qt, patching sys.exit and eventually setting up ETS""" # This doesn't create our QApplication, just holds a reference to # MAIN_APP, created above to show our splash screen as early as # possible app...
Create and show Spyder's main window Start QApplication event loop def run_spyder(app, options, args): """ Create and show Spyder's main window Start QApplication event loop """ #TODO: insert here # Main window main = MainWindow(options) try: main.setup() exce...
Main function def main(): """Main function""" # **** For Pytest **** # We need to create MainWindow **here** to avoid passing pytest # options to Spyder if running_under_pytest(): try: from unittest.mock import Mock except ImportError: from mock impo...
Create and return toolbar with *title* and *object_name* def create_toolbar(self, title, object_name, iconsize=24): """Create and return toolbar with *title* and *object_name*""" toolbar = self.addToolBar(title) toolbar.setObjectName(object_name) toolbar.setIconSize(QSize(iconsize, ...
Setup main window def setup(self): """Setup main window""" logger.info("*** Start of MainWindow setup ***") logger.info("Applying theme configuration...") ui_theme = CONF.get('appearance', 'ui_theme') color_scheme = CONF.get('appearance', 'selected') if ui_them...
Actions to be performed only after the main window's `show` method was triggered def post_visible_setup(self): """Actions to be performed only after the main window's `show` method was triggered""" self.restore_scrollbar_position.emit() # [Workaround for Issue 880] ...
Set window title. def set_window_title(self): """Set window title.""" if DEV is not None: title = u"Spyder %s (Python %s.%s)" % (__version__, sys.version_info[0], sys.version_info[1]) ...
Show a QMessageBox with a list of missing hard dependencies def report_missing_dependencies(self): """Show a QMessageBox with a list of missing hard dependencies""" missing_deps = dependencies.missing_dependencies() if missing_deps: QMessageBox.critical(self, _('Error'), ...
Load window layout settings from userconfig-based configuration with *prefix*, under *section* default: if True, do not restore inner layout def load_window_settings(self, prefix, default=False, section='main'): """Load window layout settings from userconfig-based configuration with...
Return current window settings Symetric to the 'set_window_settings' setter def get_window_settings(self): """Return current window settings Symetric to the 'set_window_settings' setter""" window_size = (self.window_size.width(), self.window_size.height()) is_fullscreen = s...
Set window settings Symetric to the 'get_window_settings' accessor def set_window_settings(self, hexstate, window_size, prefs_dialog_size, pos, is_maximized, is_fullscreen): """Set window settings Symetric to the 'get_window_settings' accessor""" self.se...
Save current window settings with *prefix* in the userconfig-based configuration, under *section* def save_current_window_settings(self, prefix, section='main', none_state=False): """Save current window settings with *prefix* in the userconfig-based conf...
Tabify plugin dockwigdets def tabify_plugins(self, first, second): """Tabify plugin dockwigdets""" self.tabifyDockWidget(first.dockwidget, second.dockwidget)
Setup window layout def setup_layout(self, default=False): """Setup window layout""" prefix = 'window' + '/' settings = self.load_window_settings(prefix, default) hexstate = settings[0] self.first_spyder_run = False if hexstate is None: # First Spyde...
Setup default layouts when run for the first time. def setup_default_layouts(self, index, settings): """Setup default layouts when run for the first time.""" self.setUpdatesEnabled(False) first_spyder_run = bool(self.first_spyder_run) # Store copy if first_spyder_run: ...
Reset window layout to default def reset_window_layout(self): """Reset window layout to default""" answer = QMessageBox.warning(self, _("Warning"), _("Window layout will be reset to default settings: " "this affects window position, size and dockwidgets.\...
Save layout dialog def quick_layout_save(self): """Save layout dialog""" get = CONF.get set_ = CONF.set names = get('quick_layouts', 'names') order = get('quick_layouts', 'order') active = get('quick_layouts', 'active') dlg = self.dialog_layout_save(self...
Layout settings dialog def quick_layout_settings(self): """Layout settings dialog""" get = CONF.get set_ = CONF.set section = 'quick_layouts' names = get(section, 'names') order = get(section, 'order') active = get(section, 'active') dlg = s...
Switch to quick layout number *index* def quick_layout_switch(self, index): """Switch to quick layout number *index*""" section = 'quick_layouts' try: settings = self.load_window_settings('layout_{}/'.format(index), section=sec...
Update the text displayed in the menu entry. def _update_show_toolbars_action(self): """Update the text displayed in the menu entry.""" if self.toolbars_visible: text = _("Hide toolbars") tip = _("Hide toolbars") else: text = _("Show toolbars") ...
Saves the name of the visible toolbars in the .ini file. def save_visible_toolbars(self): """Saves the name of the visible toolbars in the .ini file.""" toolbars = [] for toolbar in self.visible_toolbars: toolbars.append(toolbar.objectName()) CONF.set('main', 'last_visi...
Collects the visible toolbars. def get_visible_toolbars(self): """Collects the visible toolbars.""" toolbars = [] for toolbar in self.toolbarslist: if toolbar.toggleViewAction().isChecked(): toolbars.append(toolbar) self.visible_toolbars = toolbars
Loads the last visible toolbars from the .ini file. def load_last_visible_toolbars(self): """Loads the last visible toolbars from the .ini file.""" toolbars_names = CONF.get('main', 'last_visible_toolbars', default=[]) if toolbars_names: dic = {} for toolbar in se...
Show/Hides toolbars. def show_toolbars(self): """Show/Hides toolbars.""" value = not self.toolbars_visible CONF.set('main', 'toolbars_visible', value) if value: self.save_visible_toolbars() else: self.get_visible_toolbars() for toolbar i...
Handle an invalid active project. def valid_project(self): """Handle an invalid active project.""" try: path = self.projects.get_active_project_path() except AttributeError: return if bool(path): if not self.projects.is_valid_project(path): ...
Show action shortcuts in menu def show_shortcuts(self, menu): """Show action shortcuts in menu""" for element in getattr(self, menu + '_menu_actions'): if element and isinstance(element, QAction): if element._shown_shortcut is not None: element.setSh...
Hide action shortcuts in menu def hide_shortcuts(self, menu): """Hide action shortcuts in menu""" for element in getattr(self, menu + '_menu_actions'): if element and isinstance(element, QAction): if element._shown_shortcut is not None: element.setSh...
Get properties of focus widget Returns tuple (widget, properties) where properties is a tuple of booleans: (is_console, not_readonly, readwrite_editor) def get_focus_widget_properties(self): """Get properties of focus widget Returns tuple (widget, properties) where properties is a t...
Update edit menu def update_edit_menu(self): """Update edit menu""" widget, textedit_properties = self.get_focus_widget_properties() if textedit_properties is None: # widget is not an editor/console return # !!! Below this line, widget is expected to be a QPlainTextEdit...
Update search menu def update_search_menu(self): """Update search menu""" # Disabling all actions except the last one # (which is Find in files) to begin with for child in self.search_menu.actions()[:-1]: child.setEnabled(False) widget, textedit_properties = ...
Set splash message def set_splash(self, message): """Set splash message""" if self.splash is None: return if message: logger.info(message) self.splash.show() self.splash.showMessage(message, Qt.AlignBottom | Qt.AlignCenter | ...
closeEvent reimplementation def closeEvent(self, event): """closeEvent reimplementation""" if self.closing(True): event.accept() else: event.ignore()
Reimplement Qt method def resizeEvent(self, event): """Reimplement Qt method""" if not self.isMaximized() and not self.fullscreen_flag: self.window_size = self.size() QMainWindow.resizeEvent(self, event) # To be used by the tour to be able to resize self.sig_...
Reimplement Qt method def moveEvent(self, event): """Reimplement Qt method""" if not self.isMaximized() and not self.fullscreen_flag: self.window_position = self.pos() QMainWindow.moveEvent(self, event) # To be used by the tour to be able to move self.sig_mov...
Reimplement Qt method def hideEvent(self, event): """Reimplement Qt method""" try: for plugin in (self.widgetlist + self.thirdparty_plugins): if plugin.isAncestorOf(self.last_focused_widget): plugin.visibility_changed(True) QMainWindow.h...
To keep track of to the last focused widget def change_last_focused_widget(self, old, now): """To keep track of to the last focused widget""" if (now is None and QApplication.activeWindow() is not None): QApplication.activeWindow().setFocus() self.last_focused_widget = QAppl...
Exit tasks def closing(self, cancelable=False): """Exit tasks""" if self.already_closed or self.is_starting_up: return True if cancelable and CONF.get('main', 'prompt_on_exit'): reply = QMessageBox.critical(self, 'Spyder', '...
Add QDockWidget and toggleViewAction def add_dockwidget(self, child): """Add QDockWidget and toggleViewAction""" dockwidget, location = child.create_dockwidget() if CONF.get('main', 'vertical_dockwidget_titlebars'): dockwidget.setFeatures(dockwidget.features()| ...
Lock/Unlock dockwidgets and toolbars def toggle_lock(self, value): """Lock/Unlock dockwidgets and toolbars""" self.interface_locked = value CONF.set('main', 'panes_locked', value) # Apply lock to panes for plugin in (self.widgetlist + self.thirdparty_plugins): ...
Shortcut: Ctrl+Alt+Shift+M First call: maximize current dockwidget Second call (or restore=True): restore original window layout def maximize_dockwidget(self, restore=False): """Shortcut: Ctrl+Alt+Shift+M First call: maximize current dockwidget Second call (or restore=True)...
Add widget actions to toolbar def add_to_toolbar(self, toolbar, widget): """Add widget actions to toolbar""" actions = widget.toolbar_actions if actions is not None: add_actions(toolbar, actions)
Create About Spyder dialog with general information. def about(self): """Create About Spyder dialog with general information.""" versions = get_versions() # Show Git revision for development version revlink = '' if versions['revision']: rev = versions['revision...
Show Spyder's Dependencies dialog box def show_dependencies(self): """Show Spyder's Dependencies dialog box""" from spyder.widgets.dependencies import DependenciesDialog dlg = DependenciesDialog(self) dlg.set_data(dependencies.DEPENDENCIES) dlg.exec_()
Render issue before sending it to Github def render_issue(self, description='', traceback=''): """Render issue before sending it to Github""" # Get component versions versions = get_versions() # Get git revision for development version revision = '' if versions['...
Report a Spyder issue to github, generating body text if needed. def report_issue(self, body=None, title=None, open_webpage=False): """Report a Spyder issue to github, generating body text if needed.""" if body is None: from spyder.widgets.reporterror import SpyderErrorDialog ...
Global callback def global_callback(self): """Global callback""" widget = QApplication.focusWidget() action = self.sender() callback = from_qvariant(action.data(), to_text_string) from spyder.plugins.editor.widgets.editor import TextEditBaseWidget from spyder.plugi...
Open external console def open_external_console(self, fname, wdir, args, interact, debug, python, python_args, systerm, post_mortem=False): """Open external console""" if systerm: # Running script in an external system terminal try: ...
Execute lines in IPython console and eventually set focus to the Editor. def execute_in_external_console(self, lines, focus_to_editor): """ Execute lines in IPython console and eventually set focus to the Editor. """ console = self.ipyconsole console.switc...
Open filename with the appropriate application Redirect to the right widget (txt -> editor, spydata -> workspace, ...) or open file outside Spyder (if extension is not supported) def open_file(self, fname, external=False): """ Open filename with the appropriate application ...
Open external files that can be handled either by the Editor or the variable explorer inside Spyder. def open_external_file(self, fname): """ Open external files that can be handled either by the Editor or the variable explorer inside Spyder. """ fname = encoding.t...
Return Spyder PYTHONPATH def get_spyder_pythonpath(self): """Return Spyder PYTHONPATH""" active_path = [p for p in self.path if p not in self.not_active_path] return active_path + self.project_path
Add Spyder path to sys.path def add_path_to_sys_path(self): """Add Spyder path to sys.path""" for path in reversed(self.get_spyder_pythonpath()): sys.path.insert(1, path)
Remove Spyder path from sys.path def remove_path_from_sys_path(self): """Remove Spyder path from sys.path""" for path in self.path + self.project_path: while path in sys.path: sys.path.remove(path)
Spyder path manager def path_manager_callback(self): """Spyder path manager""" from spyder.widgets.pathmanager import PathManager self.remove_path_from_sys_path() project_path = self.projects.get_pythonpath() dialog = PathManager(self, self.path, project_path, ...
Projects PYTHONPATH contribution has changed def pythonpath_changed(self): """Projects PYTHONPATH contribution has changed""" self.remove_path_from_sys_path() self.project_path = self.projects.get_pythonpath() self.add_path_to_sys_path() self.sig_pythonpath_changed.emit()
Apply settings changed in 'Preferences' dialog box def apply_settings(self): """Apply settings changed in 'Preferences' dialog box""" qapp = QApplication.instance() # Set 'gtk+' as the default theme in Gtk-based desktops # Fixes Issue 2036 if is_gtk_desktop() and ('GTK+' in...
Update dockwidgets features settings def apply_panes_settings(self): """Update dockwidgets features settings""" for plugin in (self.widgetlist + self.thirdparty_plugins): features = plugin.FEATURES if CONF.get('main', 'vertical_dockwidget_titlebars'): featur...
Update status bar widgets settings def apply_statusbar_settings(self): """Update status bar widgets settings""" show_status_bar = CONF.get('main', 'show_status_bar') self.statusBar().setVisible(show_status_bar) if show_status_bar: for widget, name in ((self.mem_status...
Edit Spyder preferences def edit_preferences(self): """Edit Spyder preferences""" from spyder.preferences.configdialog import ConfigDialog dlg = ConfigDialog(self) dlg.size_change.connect(self.set_prefs_size) if self.prefs_dialog_size is not None: dlg.resize(se...
Register QAction or QShortcut to Spyder main application, with shortcut (context, name, default) def register_shortcut(self, qaction_or_qshortcut, context, name, add_sc_to_tip=False): """ Register QAction or QShortcut to Spyder main application, with short...
Apply shortcuts settings to all widgets/plugins def apply_shortcuts(self): """Apply shortcuts settings to all widgets/plugins""" toberemoved = [] for index, (qobject, context, name, add_sc_to_tip) in enumerate(self.shortcut_data): keyseq = QKeySequence( get_...
Quit and reset Spyder and then Restart application. def reset_spyder(self): """ Quit and reset Spyder and then Restart application. """ answer = QMessageBox.warning(self, _("Warning"), _("Spyder will restart and reset to default settings: <br><br>" "Do ...
Quit and Restart Spyder application. If reset True it allows to reset spyder on restart. def restart(self, reset=False): """ Quit and Restart Spyder application. If reset True it allows to reset spyder on restart. """ # Get start path to use in restart script ...
Show interactive tour. def show_tour(self, index): """Show interactive tour.""" self.maximize_dockwidget(restore=True) frames = self.tours_available[index] self.tour.set_tour(index, frames, self) self.tour.start_tour()
Open file list management dialog box. def open_fileswitcher(self, symbol=False): """Open file list management dialog box.""" if self.fileswitcher is not None and \ self.fileswitcher.is_visible: self.fileswitcher.hide() self.fileswitcher.is_visible = False ...
Add a plugin to the File Switcher. def add_to_fileswitcher(self, plugin, tabs, data, icon): """Add a plugin to the File Switcher.""" if self.fileswitcher is None: from spyder.widgets.fileswitcher import FileSwitcher self.fileswitcher = FileSwitcher(self, plugin, tabs, data, ...
Called by WorkerUpdates when ready def _check_updates_ready(self): """Called by WorkerUpdates when ready""" from spyder.widgets.helperwidgets import MessageCheckBox # feedback` = False is used on startup, so only positive feedback is # given. `feedback` = True is used when after s...
Check for spyder updates on github releases using a QThread. def check_updates(self, startup=False): """ Check for spyder updates on github releases using a QThread. """ from spyder.workers.updates import WorkerUpdates # Disable check_updates_action while the thread is wo...
Private set method def _set(self, section, option, value, verbose): """ Private set method """ if not self.has_section(section): self.add_section( section ) if not is_text_string(value): value = repr( value ) if verbose: print...
Save config into the associated .ini file def _save(self): """ Save config into the associated .ini file """ # See Issue 1086 and 1242 for background on why this # method contains all the exception handling. fname = self.filename() def _write_file(fname)...
Defines the name of the configuration file to use. def filename(self): """Defines the name of the configuration file to use.""" # Needs to be done this way to be used by the project config. # To fix on a later PR self._filename = getattr(self, '_filename', None) self._root_...
Create a .ini filename located in user home directory. This .ini files stores the global spyder preferences. def _filename_global(self): """Create a .ini filename located in user home directory. This .ini files stores the global spyder preferences. """ if self.subfolder is ...
Set configuration (not application!) version def set_version(self, version='0.0.0', save=True): """Set configuration (not application!) version""" self.set(self.DEFAULT_SECTION_NAME, 'version', version, save=save)
Load config from the associated .ini file def load_from_ini(self): """ Load config from the associated .ini file """ try: if PY2: # Python 2 fname = self.filename() if osp.isfile(fname): try: ...
Read old defaults def _load_old_defaults(self, old_version): """Read old defaults""" old_defaults = cp.ConfigParser() if check_version(old_version, '3.0.0', '<='): path = get_module_source_path('spyder') else: path = osp.dirname(self.filename()) pa...
Save new defaults def _save_new_defaults(self, defaults, new_version, subfolder): """Save new defaults""" new_defaults = DefaultsConfig(name='defaults-'+new_version, subfolder=subfolder) if not osp.isfile(new_defaults.filename()): new_defau...
Update defaults after a change in version def _update_defaults(self, defaults, old_version, verbose=False): """Update defaults after a change in version""" old_defaults = self._load_old_defaults(old_version) for section, options in defaults: for option in options: ...
Remove options which are present in the .ini file but not in defaults def _remove_deprecated_options(self, old_version): """ Remove options which are present in the .ini file but not in defaults """ old_defaults = self._load_old_defaults(old_version) for section in old_defa...
Set defaults from the current config def set_as_defaults(self): """ Set defaults from the current config """ self.defaults = [] for section in self.sections(): secdict = {} for option, value in self.items(section, raw=self.raw): se...
Reset config to Default values def reset_to_defaults(self, save=True, verbose=False, section=None): """ Reset config to Default values """ for sec, options in self.defaults: if section == None or section == sec: for option in options: ...
Private method to check section and option types def _check_section_option(self, section, option): """ Private method to check section and option types """ if section is None: section = self.DEFAULT_SECTION_NAME elif not is_text_string(section): ra...
Get Default value for a given (section, option) -> useful for type checking in 'get' method def get_default(self, section, option): """ Get Default value for a given (section, option) -> useful for type checking in 'get' method """ section = self._check_section_opt...
Get an option section=None: attribute a default section name default: default value (if not specified, an exception will be raised if option doesn't exist) def get(self, section, option, default=NoDefault): """ Get an option section=None: attribute a default sectio...
Set Default value for a given (section, option) -> called when a new (section, option) is set and no default exists def set_default(self, section, option, default_value): """ Set Default value for a given (section, option) -> called when a new (section, option) is set and no default...
Set an option section=None: attribute a default section name def set(self, section, option, value, verbose=False, save=True): """ Set an option section=None: attribute a default section name """ section = self._check_section_option(section, option) default...
Return temporary Spyder directory, checking previously that it exists. def get_temp_dir(suffix=None): """ Return temporary Spyder directory, checking previously that it exists. """ to_join = [tempfile.gettempdir()] if os.name == 'nt': to_join.append('spyder') else: use...
Return program absolute path if installed in PATH. Otherwise, return None def is_program_installed(basename): """ Return program absolute path if installed in PATH. Otherwise, return None """ for path in os.environ["PATH"].split(os.pathsep): abspath = osp.join(path, basename)...
Find program in PATH and return absolute path Try adding .exe or .bat to basename on Windows platforms (return None if not found) def find_program(basename): """ Find program in PATH and return absolute path Try adding .exe or .bat to basename on Windows platforms (return None if not ...
Given a dict, populate kwargs to create a generally useful default setup for running subprocess processes on different platforms. For example, `close_fds` is set on posix and creation of a new console window is disabled on Windows. This function will alter the given kwargs and return the...
Execute the given shell command. Note that *args and **kwargs will be passed to the subprocess call. If 'shell' is given in subprocess_kwargs it must be True, otherwise ProgramError will be raised. . If 'executable' is not given in subprocess_kwargs, it will be set to the value of ...
Run program in a separate process. NOTE: returns the process object created by `subprocess.Popen()`. This can be used with `proc.communicate()` for example. If 'shell' appears in the kwargs, it must be False, otherwise ProgramError will be raised. If only the program name is given an...
Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False. def start_file(filename): """ Generalized os.startfile for all platforms supported by Qt This function is simply wrap...
Return absolute path if Python script exists (otherwise, return None) package=None -> module is in sys.path (standard library modules) def python_script_exists(package=None, module=None): """ Return absolute path if Python script exists (otherwise, return None) package=None -> module is in sys.path...
Run Python script in a separate process package=None -> module is in sys.path (standard library modules) def run_python_script(package=None, module=None, args=[], p_args=[]): """ Run Python script in a separate process package=None -> module is in sys.path (standard library modules) """ a...
Split the string `text` using shell-like syntax This avoids breaking single/double-quoted strings (e.g. containing strings with spaces). This function is almost equivalent to the shlex.split function (see standard library `shlex`) except that it is supporting unicode strings (shlex does not suppor...
Construct Python interpreter arguments def get_python_args(fname, python_args, interact, debug, end_args): """Construct Python interpreter arguments""" p_args = [] if python_args is not None: p_args += python_args.split() if interact: p_args.append('-i') if debug: p_...
Run Python script in an external system terminal. :str wdir: working directory, may be empty. def run_python_script_in_terminal(fname, wdir, args, interact, debug, python_args, executable=None): """ Run Python script in an external system terminal. :str wdir: ...
Check version string of an active module against a required version. If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own packages up to date. Copyright (C) 20...