def argv(self): """Command to start kernels""" # Python interpreter used to start kernels if CONF.get('main_interpreter', 'default'): pyexec = get_python_executable() else: # Avoid IPython adding the virtualenv on which Spyder is running # to the kernel sys.path os.environ.pop('VIRTUAL_ENV', None) pyexec = CONF.get('main_interpreter', 'executable') # Fixes Issue #3427 if os.name == 'nt': dir_pyexec = osp.dirname(pyexec) pyexec_w = osp.join(dir_pyexec, 'pythonw.exe') if osp.isfile(pyexec_w): pyexec = pyexec_w # Command used to start kernels utils_path = osp.join(self.spy_path, 'utils', 'ipython') kernel_cmd = [ pyexec, osp.join("%s" % utils_path, "start_kernel.py"), '-f', '{connection_file}' ] return kernel_cmd
def get_font(section='appearance', option='font', font_size_delta=0): """Get console font properties depending on OS and user options""" font = FONT_CACHE.get((section, option)) if font is None: families = CONF.get(section, option+"/family", None) if families is None: return QFont() family = get_family(families) weight = QFont.Normal italic = CONF.get(section, option+'/italic', False) if CONF.get(section, option+'/bold', False): weight = QFont.Bold size = CONF.get(section, option+'/size', 9) + font_size_delta font = QFont(family, size, weight) font.setItalic(italic) FONT_CACHE[(section, option)] = font size = CONF.get(section, option+'/size', 9) + font_size_delta font.setPointSize(size) return font
def argv(self): """Command to start kernels""" # Python interpreter used to start kernels if CONF.get('main_interpreter', 'default'): pyexec = get_python_executable() else: # Avoid IPython adding the virtualenv on which Spyder is running # to the kernel sys.path os.environ.pop('VIRTUAL_ENV', None) pyexec = CONF.get('main_interpreter', 'executable') if not is_python_interpreter(pyexec): pyexec = get_python_executable() CONF.set('main_interpreter', 'executable', '') CONF.set('main_interpreter', 'default', True) CONF.set('main_interpreter', 'custom', False) # Fixes Issue #3427 if os.name == 'nt': dir_pyexec = osp.dirname(pyexec) pyexec_w = osp.join(dir_pyexec, 'pythonw.exe') if osp.isfile(pyexec_w): pyexec = pyexec_w # Command used to start kernels kernel_cmd = [ pyexec, '-m', 'spyder_kernels.console', '-f', '{connection_file}' ] return kernel_cmd
def update_preview(self, index=None, scheme_name=None): """ Update the color scheme of the preview editor and adds text. Note ---- 'index' is needed, because this is triggered by a signal that sends the selected index. """ text = ('"""A string"""\n\n' '# A comment\n\n' '# %% A cell\n\n' 'class Foo(object):\n' ' def __init__(self):\n' ' bar = 42\n' ' print(bar)\n' ) show_blanks = CONF.get('editor', 'blank_spaces') update_scrollbar = CONF.get('editor', 'scroll_past_end') if scheme_name is None: scheme_name = self.current_scheme self.preview_editor.setup_editor(linenumbers=True, markers=True, tab_mode=False, font=get_font(), show_blanks=show_blanks, color_scheme=scheme_name, scroll_past_end=update_scrollbar) self.preview_editor.set_text(text) self.preview_editor.set_language('Python')
def _get_credentials_from_settings(self): """Get the stored credentials if any.""" remember_me = CONF.get('main', 'report_error/remember_me') remember_token = CONF.get('main', 'report_error/remember_token') username = CONF.get('main', 'report_error/username', '') if not remember_me: username = '' return username, remember_me, remember_token
def _get_run_configurations(): history_count = CONF.get('run', 'history', 20) try: return [(filename, options) for filename, options in CONF.get('run', 'configurations', []) if osp.isfile(filename)][:history_count] except ValueError: CONF.set('run', 'configurations', []) return []
def update_margins(self): layout = self.layout() if self.default_margins is None: self.default_margins = layout.getContentsMargins() if CONF.get('main', 'use_custom_margin'): margin = CONF.get('main', 'custom_margin') layout.setContentsMargins(*[margin]*4) else: layout.setContentsMargins(*self.default_margins)
def update_margins(self): """Update plugin margins""" layout = self.layout() if self.default_margins is None: self.default_margins = layout.getContentsMargins() if CONF.get('main', 'use_custom_margin'): margin = CONF.get('main', 'custom_margin') layout.setContentsMargins(*[margin] * 4) else: layout.setContentsMargins(*self.default_margins)
def __init__(self, parent, history_filename, profile=False, initial_message=None, default_foreground_color=None, error_foreground_color=None, traceback_foreground_color=None, prompt_foreground_color=None, background_color=None): """ parent : specifies the parent widget """ ConsoleBaseWidget.__init__(self, parent) SaveHistoryMixin.__init__(self, history_filename) BrowseHistoryMixin.__init__(self) # Prompt position: tuple (line, index) self.current_prompt_pos = None self.new_input_line = True # History assert is_text_string(history_filename) self.history = self.load_history() # Session self.historylog_filename = CONF.get('main', 'historylog_filename', get_conf_path('history.log')) # Context menu self.menu = None self.setup_context_menu() # Simple profiling test self.profile = profile # Buffer to increase performance of write/flush operations self.__buffer = [] if initial_message: self.__buffer.append(initial_message) self.__timestamp = 0.0 self.__flushtimer = QTimer(self) self.__flushtimer.setSingleShot(True) self.__flushtimer.timeout.connect(self.flush) # Give focus to widget self.setFocus() # Cursor width self.setCursorWidth(CONF.get('main', 'cursor/width')) # Adjustments to completion_widget to use it here self.completion_widget.currentRowChanged.disconnect()
def set_color_scheme(name, color_scheme, replace=True): """Set syntax color scheme""" section = "appearance" names = CONF.get("appearance", "names", []) for key in sh.COLOR_SCHEME_KEYS: option = "%s/%s" % (name, key) value = CONF.get(section, option, default=None) if value is None or replace or name not in names: CONF.set(section, option, color_scheme[key]) names.append(to_text_string(name)) CONF.set(section, "names", sorted(list(set(names))))
def set_color_scheme(name, color_scheme, replace=True): """Set syntax color scheme""" section = "color_schemes" names = CONF.get("color_schemes", "names", []) for key in sh.COLOR_SCHEME_KEYS: option = "%s/%s" % (name, key) value = CONF.get(section, option, default=None) if value is None or replace or name not in names: CONF.set(section, option, color_scheme[key]) names.append(to_text_string(name)) CONF.set(section, "names", sorted(list(set(names))))
def is_dark_interface(): ui_theme = CONF.get('color_schemes', 'ui_theme') color_scheme = CONF.get('color_schemes', 'selected') if ui_theme == 'dark': return True elif ui_theme == 'automatic': if not is_dark_font_color(color_scheme): return True else: return False else: return False
def is_dark_interface(): ui_theme = CONF.get('appearance', 'ui_theme') color_scheme = CONF.get('appearance', 'selected') if ui_theme == 'dark': return True elif ui_theme == 'automatic': if not is_dark_font_color(color_scheme): return True else: return False else: return False
def external_editor(self, filename, goto=-1): """Edit in an external editor Recommended: SciTE (e.g. to go to line where an error did occur)""" editor_path = CONF.get("internal_console", "external_editor/path") goto_option = CONF.get("internal_console", "external_editor/gotoline") try: args = [filename] if goto > 0 and goto_option: args.append("%s%d".format(goto_option, goto)) programs.run_program(editor_path, args) except OSError: self.write_error("External editor was not found:" " %s\n" % editor_path)
def external_editor(self, filename, goto=-1): """Edit in an external editor Recommended: SciTE (e.g. to go to line where an error did occur)""" editor_path = CONF.get('internal_console', 'external_editor/path') goto_option = CONF.get('internal_console', 'external_editor/gotoline') try: args = [filename] if goto > 0 and goto_option: args.append('%s%d'.format(goto_option, goto)) programs.run_program(editor_path, args) except OSError: self.write_error("External editor was not found:" " %s\n" % editor_path)
def test_python_interpreter(tmpdir): """Test the validation of the python interpreter.""" # Set a non existing python interpreter interpreter = str(tmpdir.mkdir('interpreter').join('python')) CONF.set('main_interpreter', 'default', False) CONF.set('main_interpreter', 'custom', True) CONF.set('main_interpreter', 'executable', interpreter) # Create a kernel spec kernel_spec = SpyderKernelSpec() # Assert that the python interprerter is the default one assert interpreter not in kernel_spec.argv assert CONF.get('main_interpreter', 'default') assert not CONF.get('main_interpreter', 'custom')
def __init__(self, main=None, **kwds): """Bind widget to a QMainWindow instance""" super(SpyderPluginMixin, self).__init__(**kwds) assert self.CONF_SECTION is not None self.PLUGIN_PATH = os.path.dirname(inspect.getfile(self.__class__)) self.main = main self.default_margins = None self.plugin_actions = None self.dockwidget = None self.mainwindow = None self.ismaximized = False self.isvisible = False # NOTE: Don't use the default option of CONF.get to assign a # None shortcut to plugins that don't have one. That will mess # the creation of our Keyboard Shortcuts prefs page try: self.shortcut = CONF.get('shortcuts', '_/switch to %s' % \ self.CONF_SECTION) except configparser.NoOptionError: self.shortcut = None # We decided to create our own toggle action instead of using # the one that comes with dockwidget because it's not possible # to raise and focus the plugin with it. self.toggle_view_action = None
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.INITHISTORY[1]: rawhistory[1] = self.INITHISTORY[1] else: rawhistory = self.INITHISTORY history = [line for line in rawhistory \ if line and not line.startswith('#')] # Truncating history to X entries: while len(history) >= CONF.get('historylog', 'max_entries'): del history[0] while rawhistory[0].startswith('#'): del rawhistory[0] del rawhistory[0] # Saving truncated history: try: encoding.writelines(rawhistory, self.history_filename) except EnvironmentError: pass return history
def update_server_list(self): for language in self.configurations_for_servers: config = { 'status': self.STOPPED, 'config': CONF.get('lsp-server', language), 'instance': None } if language not in self.clients: self.clients[language] = config self.register_queue[language] = [] else: logger.debug( self.clients[language]['config'] != config['config']) current_config = self.clients[language]['config'] new_config = config['config'] restart_diff = ['cmd', 'args', 'host', 'port', 'external'] restart = any( [current_config[x] != new_config[x] for x in restart_diff]) if restart: if self.clients[language]['status'] == self.STOPPED: self.clients[language] = config elif self.clients[language]['status'] == self.RUNNING: self.close_client(language) self.clients[language] = config self.start_client(language) else: if self.clients[language]['status'] == self.RUNNING: client = self.clients[language]['instance'] client.send_plugin_configurations( new_config['configurations'])
def send_args_to_spyder(args): """ Simple socket client used to send the args passed to the Spyder executable to an already running instance. Args can be Python scripts or files with these extensions: .spydata, .mat, .npy, or .h5, which can be imported by the Variable Explorer. """ port = CONF.get('main', 'open_files_port') # Wait ~50 secs for the server to be up # Taken from https://stackoverflow.com/a/4766598/438386 for _x in range(200): try: for arg in args: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) client.connect(("127.0.0.1", port)) if is_unicode(arg): arg = arg.encode('utf-8') client.send(osp.abspath(arg)) client.close() except socket.error: time.sleep(0.25) continue break
def _create_bot(context, name): sequence = CONF.get('shortcuts', "{}/{}".format(context, name)) shortcut_editor = ShortcutEditor( shorcut_table, context, name, sequence, shortcuts) qtbot.addWidget(shortcut_editor) shortcut_editor.show() return shortcut_editor
def __init__(self, parent=None): """Initialization.""" SpyderPluginWidget.__init__(self, parent) self.explorer = ProjectExplorerWidget( self, name_filters=self.get_option('name_filters'), show_all=self.get_option('show_all'), show_hscrollbar=self.get_option('show_hscrollbar'), options_button=self.options_button, single_click_to_open=CONF.get('explorer', 'single_click_to_open'), ) layout = QVBoxLayout() layout.addWidget(self.explorer) self.setLayout(layout) self.recent_projects = self.get_option('recent_projects', default=[]) self.current_active_project = None self.latest_project = None self.watcher = WorkspaceWatcher(self) # Initialize plugin self.initialize_plugin() self.explorer.setup_project(self.get_active_project_path()) self.watcher.connect_signals(self)
def test_console_coloring(ipyconsole, qtbot): """Test that console gets the same coloring present in the Editor.""" shell = ipyconsole.get_current_shellwidget() qtbot.waitUntil(lambda: shell._prompt_html is not None, timeout=SHELL_TIMEOUT) config_options = ipyconsole.config_options() syntax_style = config_options.JupyterWidget.syntax_style style_sheet = config_options.JupyterWidget.style_sheet console_font_color = get_console_font_color(syntax_style) console_background_color = get_console_background_color(style_sheet) selected_color_scheme = CONF.get('appearance', 'selected') color_scheme = get_color_scheme(selected_color_scheme) editor_background_color = color_scheme['background'] editor_font_color = color_scheme['normal'][0] console_background_color = console_background_color.replace("'", "") editor_background_color = editor_background_color.replace("'", "") console_font_color = console_font_color.replace("'", "") editor_font_color = editor_font_color.replace("'", "") assert console_background_color.strip() == editor_background_color.strip() assert console_font_color.strip() == editor_font_color.strip()
def send_args_to_spyder(args): """ Simple socket client used to send the args passed to the Spyder executable to an already running instance. Args can be Python scripts or files with these extensions: .spydata, .mat, .npy, or .h5, which can be imported by the Variable Explorer. """ port = CONF.get('main', 'open_files_port') # Wait ~50 secs for the server to be up # Taken from http://stackoverflow.com/a/4766598/438386 for _x in range(200): try: for arg in args: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) client.connect(("127.0.0.1", port)) if is_unicode(arg): arg = arg.encode('utf-8') client.send(osp.abspath(arg)) client.close() except socket.error: time.sleep(0.25) continue break
def _load_all_bookmarks(): """Load all bookmarks from config.""" slots = CONF.get('editor', 'bookmarks', {}) for slot_num in list(slots.keys()): if not osp.isfile(slots[slot_num][0]): slots.pop(slot_num) return slots
def traceback_available(self, text): """Traceback is available in the internal console: showing the internal console automatically to warn the user""" if CONF.get('main', 'show_internal_console_if_traceback', False): self.dockwidget.show() self.dockwidget.raise_() else: if self.msgbox_traceback is None: self.msgbox_traceback = QMessageBox( QMessageBox.Critical, _('Error'), _("<b>Spyder has encountered a problem.</b><br>" "Sorry for the inconvenience." "<br><br>" "You can automatically submit this error to our Github " "issues tracker.<br><br>" "<i>Note:</i> You need a Github account for that."), QMessageBox.Ok, parent=self) self.submit_btn = self.msgbox_traceback.addButton( _('Submit to Github'), QMessageBox.YesRole) self.submit_btn.pressed.connect(self.press_submit_btn) self.msgbox_traceback.setWindowModality(Qt.NonModal) self.error_traceback = "" self.msgbox_traceback.show() self.msgbox_traceback.finished.connect(self.close_msg) self.error_traceback += text self.msgbox_traceback.setDetailedText(self.error_traceback)
def _create_bot(context, name): sequence = CONF.get('shortcuts', "{}/{}".format(context, name)) shortcut_editor = ShortcutEditor(shortcut_table, context, name, sequence, shortcuts) qtbot.addWidget(shortcut_editor) shortcut_editor.show() return shortcut_editor
def exception_occurred(self, text, is_traceback): """ Exception ocurred in the internal console. Show a QDialog or the internal console to warn the user. """ # Skip errors without traceback or dismiss if (not is_traceback and self.error_dlg is None) or self.dimiss_error: return if CONF.get('main', 'show_internal_console_if_traceback'): self.dockwidget.show() self.dockwidget.raise_() else: if self.error_dlg is None: self.error_dlg = SpyderErrorDialog(self) self.error_dlg.dimiss_btn.clicked.connect( self.dismiss_error_dlg) self.error_dlg.rejected.connect(self.remove_error_dlg) self.error_dlg.details.go_to_error.connect(self.go_to_error) self.error_dlg.show() self.error_dlg.append_traceback(text)
def argv(self): """Command to start kernels""" # Python interpreter used to start kernels if self.default_interpreter: pyexec = get_python_executable() else: # Avoid IPython adding the virtualenv on which Spyder is running # to the kernel sys.path os.environ.pop('VIRTUAL_ENV', None) pyexec = CONF.get('main_interpreter', 'executable') # Fixes Issue #3427 if os.name == 'nt': dir_pyexec = osp.dirname(pyexec) pyexec_w = osp.join(dir_pyexec, 'pythonw.exe') if osp.isfile(pyexec_w): pyexec = pyexec_w # Command used to start kernels utils_path = osp.join(self.spy_path, 'utils', 'ipython') kernel_cmd = [ pyexec, osp.join("%s" % utils_path, "start_kernel.py"), '-f', '{connection_file}' ] return kernel_cmd
def update_font(self): """Update font from Preferences""" font = self.get_plugin_font() for shellwidget in self.shellwidgets: shellwidget.shell.set_font(font) completion_size = CONF.get('main', 'completion/size') comp_widget = shellwidget.shell.completion_widget comp_widget.setup_appearance(completion_size, font)
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, parent=self.editor) dialog.exec_if_nonempty() self.recover_files_to_open = dialog.files_to_open[:]
def __init__(self, fname=None): self.args = None self.args_enabled = None self.wdir = None self.wdir_enabled = None self.current = None self.systerm = None self.interact = None self.show_kill_warning = None self.post_mortem = None self.python_args = None self.python_args_enabled = None self.set(CONF.get('run', 'defaultconfiguration', default={})) if fname is not None and\ CONF.get('run', WDIR_USE_SCRIPT_DIR_OPTION, True): self.wdir = osp.dirname(fname) self.wdir_enabled = True
def __init__(self, fname=None): self.args = None self.args_enabled = None self.wdir = None self.wdir_enabled = None self.current = None self.systerm = None self.interact = None self.show_kill_warning =None self.post_mortem = None self.python_args = None self.python_args_enabled = None self.set(CONF.get('run', 'defaultconfiguration', default={})) if fname is not None and\ CONF.get('run', WDIR_USE_SCRIPT_DIR_OPTION, True): self.wdir = osp.dirname(fname) self.wdir_enabled = True
def get_foreground_color(): """ Get main color for the icons based on the color theme and color scheme currently selected. """ ui_theme = CONF.get('color_schemes', 'ui_theme') color_scheme = CONF.get('color_schemes', 'selected') if ui_theme == 'dark': foreground_color = 'white' elif ui_theme == 'automatic': if not is_dark_font_color(color_scheme): foreground_color = 'white' else: foreground_color = 'black' else: foreground_color = 'black' return foreground_color
def shellwidget_config(self): """ Generate a Config instance for shell widgets using our config system This lets us create each widget with its own config (as opposed to IPythonQtConsoleApp, where all widgets have the same config) """ # ---- IPython config ---- try: profile_path = osp.join(get_ipython_dir(), 'profile_default') full_ip_cfg = load_pyconfig_files(['ipython_qtconsole_config.py'], profile_path) # From the full config we only select the IPythonWidget section # because the others have no effect here. ip_cfg = Config({'IPythonWidget': full_ip_cfg.IPythonWidget}) except: ip_cfg = Config() # ---- Spyder config ---- spy_cfg = Config() # Make the pager widget a rich one (i.e a QTextEdit) spy_cfg.IPythonWidget.kind = 'rich' # Gui completion widget completion_type_o = CONF.get('ipython_console', 'completion_type') completions = {0: "droplist", 1: "ncurses", 2: "plain"} spy_cfg.IPythonWidget.gui_completion = completions[completion_type_o] # Pager pager_o = self.get_option('use_pager') if pager_o: spy_cfg.IPythonWidget.paging = 'inside' else: spy_cfg.IPythonWidget.paging = 'none' # Calltips calltips_o = self.get_option('show_calltips') spy_cfg.IPythonWidget.enable_calltips = calltips_o # Buffer size buffer_size_o = self.get_option('buffer_size') spy_cfg.IPythonWidget.buffer_size = buffer_size_o # Prompts in_prompt_o = self.get_option('in_prompt') out_prompt_o = self.get_option('out_prompt') if in_prompt_o: spy_cfg.IPythonWidget.in_prompt = in_prompt_o if out_prompt_o: spy_cfg.IPythonWidget.out_prompt = out_prompt_o # Merge IPython and Spyder configs. Spyder prefs will have prevalence # over IPython ones ip_cfg._merge(spy_cfg) return ip_cfg
def __init__(self, parent, history_filename, profile=False): """ parent : specifies the parent widget """ ConsoleBaseWidget.__init__(self, parent) SaveHistoryMixin.__init__(self) # Prompt position: tuple (line, index) self.current_prompt_pos = None self.new_input_line = True # History self.histidx = None self.hist_wholeline = False assert is_text_string(history_filename) self.history_filename = history_filename self.history = self.load_history() # Session self.historylog_filename = CONF.get('main', 'historylog_filename', get_conf_path('history.log')) # Context menu self.menu = None self.setup_context_menu() # Simple profiling test self.profile = profile # Buffer to increase performance of write/flush operations self.__buffer = [] self.__buffer.append("NOTE: The Python console is going to " "be REMOVED in Spyder 3.2. Please start " "to migrate your work to the " "IPython console instead.\n\n") self.__timestamp = 0.0 self.__flushtimer = QTimer(self) self.__flushtimer.setSingleShot(True) self.__flushtimer.timeout.connect(self.flush) # Give focus to widget self.setFocus() # Cursor width self.setCursorWidth( CONF.get('main', 'cursor/width') )
def lsp_client(qtbot): config = CONF.get('lsp-server', 'python') lsp_editor = LSPEditor() lsp = LSPClient(parent=None, server_settings=config, language='python') lsp.register_plugin_type(LSPEventTypes.DOCUMENT, lsp_editor.sig_lsp_notification) yield lsp, lsp_editor if os.name != 'nt': lsp.stop()
def _get_inspect_shortcut(self): """ Queries the editor's config to get the current "Inspect" shortcut. """ value = CONF.get('shortcuts', 'editor/inspect current object') if value: if sys.platform == "darwin": value = value.replace('Ctrl', 'Cmd') return value
def get_settings(): """ Return Variable Explorer settings dictionary (i.e. namespace browser settings according to Spyder's configuration file) """ settings = {} # CONF.load_from_ini() # necessary only when called from another process for name in REMOTE_SETTINGS: settings[name] = CONF.get(VariableExplorer.CONF_SECTION, name) return settings
def _banner_default(self): """ Reimplement banner creation to let the user decide if he wants a banner or not """ banner_o = CONF.get('ipython_console', 'show_banner', True) if banner_o: return self.long_banner() else: return self.short_banner()
def __init__(self, parent=None, namespace=None, commands=[], message=None, max_line_count=300, font=None, exitfunc=None, profile=False, multithreaded=True, light_background=True): PythonShellWidget.__init__(self, parent, get_conf_path('history_internal.py'), profile) self.set_light_background(light_background) self.multithreaded = multithreaded self.setMaximumBlockCount(max_line_count) # For compatibility with ExtPythonShellWidget self.is_ipykernel = False if font is not None: self.set_font(font) # Allow raw_input support: self.input_loop = None self.input_mode = False # KeyboardInterrupt support self.interrupted = False # used only for not-multithreaded mode self.sig_keyboard_interrupt.connect(self.keyboard_interrupt) # Code completion / calltips getcfg = lambda option: CONF.get('internal_console', option) case_sensitive = getcfg('codecompletion/case_sensitive') self.set_codecompletion_case(case_sensitive) # keyboard events management self.eventqueue = [] # Init interpreter self.exitfunc = exitfunc self.commands = commands self.message = message self.interpreter = None self.start_interpreter(namespace) # Clear status bar self.status.emit('') # Embedded shell -- requires the monitor (which installs the # 'open_in_spyder' function in builtins) if hasattr(builtins, 'open_in_spyder'): self.go_to_error.connect(self.open_with_external_spyder)
def set_spyder_breakpoints(self): self.clear_all_breaks() #------Really deleting all breakpoints: for bp in bdb.Breakpoint.bpbynumber: if bp: bp.deleteMe() bdb.Breakpoint.next = 1 bdb.Breakpoint.bplist = {} bdb.Breakpoint.bpbynumber = [None] #------ from spyder.config.main import CONF CONF.load_from_ini() if CONF.get('run', 'breakpoints/enabled', True): breakpoints = CONF.get('run', 'breakpoints', {}) i = 0 for fname, data in list(breakpoints.items()): for linenumber, condition in data: i += 1 self.set_break(self.canonic(fname), linenumber, cond=condition)
def _spyder_run_setting_is_correct(): try: # This is the spyder 3 location from spyder.config.main import CONF except ImportError: # CONF moved in spyder 4 from spyder.config.manager import CONF # Use this instead of accessing like a dictionary so that a # default value can be supplied if the setting is missing. return CONF.get('run', 'default/interpreter/dedicated', False)
def __init__(self, parent, history_filename, profile=False): """ parent : specifies the parent widget """ ConsoleBaseWidget.__init__(self, parent) SaveHistoryMixin.__init__(self) # Prompt position: tuple (line, index) self.current_prompt_pos = None self.new_input_line = True # History self.histidx = None self.hist_wholeline = False assert is_text_string(history_filename) self.history_filename = history_filename self.history = self.load_history() # Session self.historylog_filename = CONF.get('main', 'historylog_filename', get_conf_path('history.log')) # Context menu self.menu = None self.setup_context_menu() # Simple profiling test self.profile = profile # Buffer to increase performance of write/flush operations self.__buffer = [] self.__timestamp = 0.0 self.__flushtimer = QTimer(self) self.__flushtimer.setSingleShot(True) self.__flushtimer.timeout.connect(self.flush) # Give focus to widget self.setFocus() # Cursor width self.setCursorWidth( CONF.get('main', 'cursor/width') )
def lsp_client(qtbot): config = CONF.get('lsp-server', 'python') lsp_editor = LSPEditor() lsp = LSPClient(None, config['args'], config, config['external'], plugin_configurations=config.get('configurations', {}), language='python') lsp.register_plugin_type( LSPEventTypes.DOCUMENT, lsp_editor.sig_lsp_notification) # qtbot.addWidget(lsp) yield lsp, lsp_editor if os.name != 'nt': lsp.stop()
def __init__( self, parent=None, namespace=None, commands=[], message=None, max_line_count=300, font=None, exitfunc=None, profile=False, multithreaded=True, light_background=True, ): PythonShellWidget.__init__(self, parent, get_conf_path("history_internal.py"), profile) self.set_light_background(light_background) self.multithreaded = multithreaded self.setMaximumBlockCount(max_line_count) if font is not None: self.set_font(font) # Allow raw_input support: self.input_loop = None self.input_mode = False # KeyboardInterrupt support self.interrupted = False # used only for not-multithreaded mode self.sig_keyboard_interrupt.connect(self.keyboard_interrupt) # Code completion / calltips getcfg = lambda option: CONF.get("internal_console", option) case_sensitive = getcfg("codecompletion/case_sensitive") self.set_codecompletion_case(case_sensitive) # keyboard events management self.eventqueue = [] # Init interpreter self.exitfunc = exitfunc self.commands = commands self.message = message self.interpreter = None self.start_interpreter(namespace) # Clear status bar self.status.emit("") # Embedded shell -- requires the monitor (which installs the # 'open_in_spyder' function in builtins) if hasattr(builtins, "open_in_spyder"): self.go_to_error.connect(self.open_with_external_spyder)
def test_set_sequence_to_default(create_shortcut_editor, qtbot): """ Test that clicking on the button 'Default' set the sequence in the Shortcut Editor to the default value as espected. """ shortcut_editor = create_shortcut_editor('editor', 'delete line') default_sequence = CONF.get( 'shortcuts', "{}/{}".format('editor', 'delete line')) qtbot.mouseClick(shortcut_editor.button_default, Qt.LeftButton) assert shortcut_editor.new_sequence == default_sequence assert shortcut_editor.warning == NO_WARNING assert shortcut_editor.button_ok.isEnabled()
def set_spyder_breakpoints(self, force=False): """Set Spyder breakpoints into a debugging session""" if self._reading or force: breakpoints_dict = CONF.get('run', 'breakpoints', {}) # We need to enclose pickled values in a list to be able to # send them to the kernel in Python 2 serialiazed_breakpoints = [pickle.dumps(breakpoints_dict, protocol=PICKLE_PROTOCOL)] breakpoints = to_text_string(serialiazed_breakpoints) cmd = u"!get_ipython().kernel._set_spyder_breakpoints({})" self.kernel_client.input(cmd.format(breakpoints))
def icon(name, resample=False, icon_path=None): theme = CONF.get('main', 'icon_theme') if theme == 'spyder 3': if not _resource['loaded']: qta.load_font('spyder', 'spyder.ttf', 'spyder-charmap.json', directory=_resource['directory']) _resource['loaded'] = True args, kwargs = _qtaargs[name] return qta.icon(*args, **kwargs) elif theme == 'spyder 2': icon = get_icon(name + '.png', resample=resample) if icon_path: icon_path = osp.join(icon_path, name + '.png') if osp.isfile(icon_path): icon = QIcon(icon_path) return icon if icon is not None else QIcon()
def __init__(self, main=None): """Bind widget to a QMainWindow instance.""" super(PluginWidget, self).__init__(main) assert self.CONF_SECTION is not None self.dockwidget = None self.undocked_window = None # Check compatibility check_compatibility, message = self.check_compatibility() if not check_compatibility: self.show_compatibility_message(message) self.PLUGIN_PATH = os.path.dirname(inspect.getfile(self.__class__)) self.main = main self.default_margins = None self.plugin_actions = None self.ismaximized = False self.isvisible = False # Options button and menu self.options_button = create_toolbutton(self, text=_('Options'), icon=ima.icon('tooloptions')) self.options_button.setPopupMode(QToolButton.InstantPopup) # Don't show menu arrow and remove padding if is_dark_interface(): self.options_button.setStyleSheet( ("QToolButton::menu-indicator{image: none;}\n" "QToolButton{padding: 3px;}")) else: self.options_button.setStyleSheet( "QToolButton::menu-indicator{image: none;}") self.options_menu = QMenu(self) # NOTE: Don't use the default option of CONF.get to assign a # None shortcut to plugins that don't have one. That will mess # the creation of our Keyboard Shortcuts prefs page try: self.shortcut = CONF.get('shortcuts', '_/switch to %s' % self.CONF_SECTION) except configparser.NoOptionError: pass # We decided to create our own toggle action instead of using # the one that comes with dockwidget because it's not possible # to raise and focus the plugin with it. self.toggle_view_action = None
def __init__(self, fname=None): self.args = None self.args_enabled = None self.wdir = None self.wdir_enabled = None self.current = None self.systerm = None self.interact = None self.post_mortem = None self.python_args = None self.python_args_enabled = None self.clear_namespace = None self.file_dir = None self.cw_dir = None self.fixed_dir = None self.dir = None self.set(CONF.get('run', 'defaultconfiguration', default={}))