def load_and_translate(self, sbmlfile, pythonfile, editor, set_current=True): """ Read filename as combine archive, unzip, translate, reconstitute in Python, and create an editor instance and return it *Warning* This is loading file, creating editor but not executing the source code analysis -- the analysis must be done by the editor plugin (in case multiple editorstack instances are handled) """ sbmlfile = str(sbmlfile) self.emit(SIGNAL('starting_long_process(QString)'), _("Loading %s...") % sbmlfile) text, enc = encoding.read(sbmlfile) sbmlstr = te.readFromFile(sbmlfile) text = "import tellurium as te\n\nr = te.loada('''\n" + str(te.sbmlToAntimony(sbmlstr)) + "''')" widgeteditor = editor.editorstacks[0] finfo = widgeteditor.create_new_editor(pythonfile, enc, text, set_current, new=True) index = widgeteditor.data.index(finfo) widgeteditor._refresh_outlineexplorer(index, update=True) self.emit(SIGNAL('ending_long_process(QString)'), "") if widgeteditor.isVisible() and widgeteditor.checkeolchars_enabled \ and sourcecode.has_mixed_eol_chars(text): name = os.path.basename(pythonfile) QMessageBox.warning(self, widgeteditor.title, _("<b>%s</b> contains mixed end-of-line " "characters.<br>Spyder will fix this " "automatically.") % name, QMessageBox.Ok) widgeteditor.set_os_eol_chars(index) widgeteditor.is_analysis_done = False finfo.editor.set_cursor_position('eof') finfo.editor.insert_text(os.linesep) return finfo, sbmlfile
def setData(self, index, value, role=Qt.EditRole): """Cell content change""" if not index.isValid() or self.readonly: return False i = index.row() j = index.column() value = from_qvariant(value, str) if self._data.dtype.name == "bool": try: val = bool(float(value)) except ValueError: val = value.lower() == "true" elif self._data.dtype.name.startswith("string"): val = str(value) elif self._data.dtype.name.startswith("unicode"): val = unicode(value) else: if value.lower().startswith('e') or value.lower().endswith('e'): return False try: val = complex(value) if not val.imag: val = val.real except ValueError, e: QMessageBox.critical(self.dialog, "Error", "Value error: %s" % str(e)) return False
def run_script_in_current_client(self, filename, wdir, args, debug): """Run script in current client, if any""" norm = lambda text: remove_backslashes(to_text_string(text)) client = self.get_current_client() if client is not None: # Internal kernels, use runfile if client.kernel_widget_id is not None: line = "%s('%s'" % ('debugfile' if debug else 'runfile', norm(filename)) if args: line += ", args='%s'" % norm(args) if wdir: line += ", wdir='%s'" % norm(wdir) line += ")" else: # External kernels, use %run line = "%run " if debug: line += "-d " line += "\"%s\"" % to_text_string(filename) if args: line += " %s" % norm(args) self.execute_python_code(line) self.visibility_changed(True) self.raise_() else: #XXX: not sure it can really happen QMessageBox.warning(self, _('Warning'), _("No IPython console is currently available to run <b>%s</b>." "<br><br>Please open a new one and try again." ) % osp.basename(filename), QMessageBox.Ok)
def _sel_to_text(self, cell_range): """Copy an array portion to a unicode string""" if not cell_range: return row_min, row_max, col_min, col_max = get_idx_rect(cell_range) if col_min == 0 and col_max == (self.model().cols_loaded - 1): # we've selected a whole column. It isn't possible to # select only the first part of a column without loading more, # so we can treat it as intentional and copy the whole thing col_max = self.model().total_cols - 1 if row_min == 0 and row_max == (self.model().rows_loaded - 1): row_max = self.model().total_rows - 1 _data = self.model().get_data() if PY3: output = io.BytesIO() else: output = io.StringIO() try: np.savetxt(output, _data[row_min:row_max + 1, col_min:col_max + 1], delimiter='\t') except: QMessageBox.warning( self, _("Warning"), _("It was not possible to copy values for " "this array")) return contents = output.getvalue().decode('utf-8') output.close() return contents
def setData(self, index, value, role=Qt.EditRole, change_type=None): """Cell content change""" column = index.column() row = index.row() if change_type is not None: try: value = self.data(index, role=Qt.DisplayRole) val = from_qvariant(value, str) if change_type is bool: val = bool_false_check(val) self.df.iloc[row, column - 1] = change_type(val) except ValueError: self.df.iloc[row, column - 1] = change_type('0') else: val = from_qvariant(value, str) current_value = self.get_value(row, column-1) if isinstance(current_value, bool): val = bool_false_check(val) if isinstance(current_value, ((bool,) + _sup_nr + _sup_com)) or \ is_text_string(current_value): try: self.df.iloc[row, column-1] = current_value.__class__(val) except ValueError as e: QMessageBox.critical(self.dialog, "Error", "Value error: %s" % str(e)) return False else: QMessageBox.critical(self.dialog, "Error", "The type of the cell is not a supported " "type") return False self.max_min_col_update() return True
def set_user_env(reg, parent=None): """Set HKCU (current user) environment variables""" reg = listdict2envdict(reg) types = dict() key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") for name in reg: try: _x, types[name] = winreg.QueryValueEx(key, name) except WindowsError: types[name] = winreg.REG_EXPAND_SZ key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_SET_VALUE) for name in reg: winreg.SetValueEx(key, name, 0, types[name], reg[name]) try: from win32gui import SendMessageTimeout from win32con import (HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG) SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", SMTO_ABORTIFHUNG, 5000) except ImportError: QMessageBox.warning( parent, _("Warning"), _("Module <b>pywin32 was not found</b>.<br>" "Please restart this Windows <i>session</i> " "(not the computer) for changes to take effect."))
def move(self, fnames=None): """Move files/directories""" if fnames is None: fnames = self.get_selected_filenames() orig = fixpath(osp.dirname(fnames[0])) while True: self.parent_widget.redirect_stdio.emit(False) folder = getexistingdirectory(self, _("Select directory"), orig) self.parent_widget.redirect_stdio.emit(True) if folder: folder = fixpath(folder) if folder != orig: break else: return for fname in fnames: basename = osp.basename(fname) try: misc.move_file(fname, osp.join(folder, basename)) except EnvironmentError as error: QMessageBox.critical( self, _("Error"), _("<b>Unable to move <i>%s</i></b>" "<br><br>Error message:<br>%s") % (basename, to_text_string(error)))
def chdir(self, directory=None, browsing_history=False): """Set directory as working directory""" if directory is not None: directory = osp.abspath(to_text_string(directory)) if browsing_history: directory = self.history[self.histindex] elif directory in self.history: self.histindex = self.history.index(directory) else: if self.histindex is None: self.history = [] else: self.history = self.history[:self.histindex + 1] if len(self.history) == 0 or \ (self.history and self.history[-1] != directory): self.history.append(directory) self.histindex = len(self.history) - 1 directory = to_text_string(directory) try: os.chdir(directory) self.parent_widget.open_dir.emit(directory) self.refresh(new_path=directory, force_current=True) except PermissionError: QMessageBox.critical( self.parent_widget, "Error", _("You don't have the right permissions to " "open this directory"))
def load_and_translate(self, combine, pythonfile, editor, set_current=True): """ Read filename as combine archive, unzip, translate, reconstitute in Python, and create an editor instance and return it *Warning* This is loading file, creating editor but not executing the source code analysis -- the analysis must be done by the editor plugin (in case multiple editorstack instances are handled) """ combine = str(combine) self.emit(SIGNAL('starting_long_process(QString)'), _("Loading %s...") % combine) text, enc = encoding.read(combine) text = Translatecombine(combine) zipextloctemp, sbmlloclisttemp, sedmlloclisttemp = manifestsearch(combine) for i in range(len(text)): widgeteditor = editor.editorstacks[0] sedmlfname = os.path.basename(sedmlloclisttemp[i]) finfo = widgeteditor.create_new_editor(os.path.splitext(sedmlfname)[0] + '.py', enc, text[i], set_current, new=True) index = widgeteditor.data.index(finfo) widgeteditor._refresh_outlineexplorer(index, update=True) self.emit(SIGNAL('ending_long_process(QString)'), "") if widgeteditor.isVisible() and widgeteditor.checkeolchars_enabled \ and sourcecode.has_mixed_eol_chars(text[i]): name = os.path.basename(os.path.splitext(sedmlfname)[0] + '.py') QMessageBox.warning(self, widgeteditor.title, _("<b>%s</b> contains mixed end-of-line " "characters.<br>Spyder will fix this " "automatically.") % name, QMessageBox.Ok) widgeteditor.set_os_eol_chars(index) widgeteditor.is_analysis_done = False finfo.editor.set_cursor_position('eof') finfo.editor.insert_text(os.linesep) return finfo, combine
def launch_error_message(self, error_type, error=None): """Launch a message box with a predefined error message. Parameters ---------- error_type : int [CLOSE_ERROR, RESET_ERROR, RESTART_ERROR] Possible error codes when restarting/reseting spyder. error : Exception Actual Python exception error caught. """ messages = {CLOSE_ERROR: _("It was not possible to close the previous " "Spyder instance.\nRestart aborted."), RESET_ERROR: _("Spyder could not reset to factory " "defaults.\nRestart aborted."), RESTART_ERROR: _("It was not possible to restart Spyder.\n" "Operation aborted.")} titles = {CLOSE_ERROR: _("Spyder exit error"), RESET_ERROR: _("Spyder reset error"), RESTART_ERROR: _("Spyder restart error")} if error: e = error.__repr__() message = messages[error_type] + _("\n\n{0}").format(e) else: message = messages[error_type] title = titles[error_type] self.splash.hide() QMessageBox.warning(self, title, message, QMessageBox.Ok) raise RuntimeError(message)
def rename_file(self, fname): """Rename file""" path, valid = QInputDialog.getText(self, _("Rename"), _("New name:"), QLineEdit.Normal, osp.basename(fname)) if valid: path = osp.join(osp.dirname(fname), to_text_string(path)) if path == fname: return if osp.exists(path): if ( QMessageBox.warning( self, _("Rename"), _("Do you really want to rename <b>%s</b> and " "overwrite the existing file <b>%s</b>?") % (osp.basename(fname), osp.basename(path)), QMessageBox.Yes | QMessageBox.No, ) == QMessageBox.No ): return try: misc.rename_file(fname, path) self.parent_widget.renamed.emit(fname, path) return path except EnvironmentError as error: QMessageBox.critical( self, _("Rename"), _("<b>Unable to rename file <i>%s</i></b>" "<br><br>Error message:<br>%s") % (osp.basename(fname), to_text_string(error)), )
def _sel_to_text(self, cell_range): """Copy an array portion to a unicode string""" if not cell_range: return row_min, row_max, col_min, col_max = get_idx_rect(cell_range) if col_min == 0 and col_max == (self.model().cols_loaded-1): # we've selected a whole column. It isn't possible to # select only the first part of a column without loading more, # so we can treat it as intentional and copy the whole thing col_max = self.model().total_cols-1 if row_min == 0 and row_max == (self.model().rows_loaded-1): row_max = self.model().total_rows-1 _data = self.model().get_data() if PY3: output = io.BytesIO() else: output = io.StringIO() try: np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1], delimiter='\t') except: QMessageBox.warning(self, _("Warning"), _("It was not possible to copy values for " "this array")) return contents = output.getvalue().decode('utf-8') output.close() return contents
def help(self): """Help on Spyder console""" QMessageBox.about( self, _("Help"), """<b>%s</b> <p><i>%s</i><br> edit foobar.py <p><i>%s</i><br> xedit foobar.py <p><i>%s</i><br> run foobar.py <p><i>%s</i><br> clear x, y <p><i>%s</i><br> !ls <p><i>%s</i><br> object? <p><i>%s</i><br> result = oedit(object) """ % ( _("Shell special commands:"), _("Internal editor:"), _("External editor:"), _("Run script:"), _("Remove references:"), _("System commands:"), _("Python help:"), _("GUI-based editor:"), ), )
def run_script_in_current_client(self, filename, wdir, args, debug): """Run script in current client, if any""" norm = lambda text: remove_backslashes(to_text_string(text)) client = self.get_current_client() if client is not None: # Internal kernels, use runfile if client.kernel_widget_id is not None: line = "%s('%s'" % ('debugfile' if debug else 'runfile', norm(filename)) if args: line += ", args='%s'" % norm(args) if wdir: line += ", wdir='%s'" % norm(wdir) line += ")" else: # External kernels, use %run line = "%run " if debug: line += "-d " line += "\"%s\"" % to_text_string(filename) if args: line += " %s" % norm(args) self.execute_python_code(line) self.visibility_changed(True) self.raise_() else: #XXX: not sure it can really happen QMessageBox.warning( self, _('Warning'), _("No IPython console is currently available to run <b>%s</b>." "<br><br>Please open a new one and try again.") % osp.basename(filename), QMessageBox.Ok)
def start(self, wdir=None, args=None, pythonpath=None): filename = to_text_string(self.filecombo.currentText()) if wdir is None: wdir = self._last_wdir if wdir is None: wdir = osp.basename(filename) if args is None: args = self._last_args if args is None: args = [] if pythonpath is None: pythonpath = self._last_pythonpath self._last_wdir = wdir self._last_args = args self._last_pythonpath = pythonpath self.datelabel.setText(_('Profiling, please wait...')) self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.SeparateChannels) self.process.setWorkingDirectory(wdir) self.connect(self.process, SIGNAL("readyReadStandardOutput()"), self.read_output) self.connect(self.process, SIGNAL("readyReadStandardError()"), lambda: self.read_output(error=True)) self.connect(self.process, SIGNAL("finished(int,QProcess::ExitStatus)"), self.finished) self.connect(self.stop_button, SIGNAL("clicked()"), self.process.kill) if pythonpath is not None: env = [to_text_string(_pth) for _pth in self.process.systemEnvironment()] baseshell.add_pathlist_to_PYTHONPATH(env, pythonpath) self.process.setEnvironment(env) self.output = '' self.error_output = '' p_args = ['-m', 'cProfile', '-o', self.DATAPATH] if os.name == 'nt': # On Windows, one has to replace backslashes by slashes to avoid # confusion with escape characters (otherwise, for example, '\t' # will be interpreted as a tabulation): p_args.append(osp.normpath(filename).replace(os.sep, '/')) else: p_args.append(filename) if args: p_args.extend(shell_split(args)) executable = sys.executable if executable.endswith("spyder.exe"): # py2exe distribution executable = "python.exe" self.process.start(executable, p_args) running = self.process.waitForStarted() self.set_running_state(running) if not running: QMessageBox.critical(self, _("Error"), _("Process failed to start"))
def _set_step(self, step): """Proceed to a given step""" new_tab = self.tab_widget.currentIndex() + step assert new_tab < self.tab_widget.count() and new_tab >= 0 if new_tab == self.tab_widget.count() - 1: try: self.table_widget.open_data( self._get_plain_text(), self.text_widget.get_col_sep(), self.text_widget.get_row_sep(), self.text_widget.trnsp_box.isChecked(), self.text_widget.get_skiprows(), self.text_widget.get_comments(), ) self.done_btn.setEnabled(True) self.done_btn.setDefault(True) self.fwd_btn.setEnabled(False) self.back_btn.setEnabled(True) except (SyntaxError, AssertionError) as error: QMessageBox.critical( self, _("Import wizard"), _( "<b>Unable to proceed to next step</b>" "<br><br>Please check your entries." "<br><br>Error message:<br>%s" ) % str(error), ) return elif new_tab == 0: self.done_btn.setEnabled(False) self.fwd_btn.setEnabled(True) self.back_btn.setEnabled(False) self._focus_tab(new_tab)
def move(self, fnames=None): """Move files/directories""" if fnames is None: fnames = self.get_selected_filenames() orig = fixpath(osp.dirname(fnames[0])) while True: self.parent_widget.redirect_stdio.emit(False) folder = getexistingdirectory(self, _("Select directory"), orig) self.parent_widget.redirect_stdio.emit(True) if folder: folder = fixpath(folder) if folder != orig: break else: return for fname in fnames: basename = osp.basename(fname) try: misc.move_file(fname, osp.join(folder, basename)) except EnvironmentError as error: QMessageBox.critical( self, _("Error"), _("<b>Unable to move <i>%s</i></b>" "<br><br>Error message:<br>%s") % (basename, to_text_string(error)), )
def load_and_translate(self, sedmlfile, pythonfile, editor, set_current=True): """ Read filename as SED-ML file, translate it to Python, and create an editor instance and return it *Warning* This is loading file, creating editor but not executing the source code analysis -- the analysis must be done by the editor plugin (in case multiple editorstack instances are handled) """ #sedmlfile = to_text_string(sedmlfile) sedmlfile = str(sedmlfile) self.emit(SIGNAL('starting_long_process(QString)'), _("Loading %s...") % sedmlfile) text, enc = encoding.read(sedmlfile) fname = os.path.basename(sedmlfile) temp = '"End of code generated by Import SED-ML plugin ' + time.strftime("%m/%d/%Y") + '"\n"Extracted from ' + fname + '"\n\n' text = te.sedmlToPython(sedmlfile) + temp widgeteditor = editor.editorstacks[0] finfo = widgeteditor.create_new_editor(pythonfile, enc, text, set_current, new=True) index = widgeteditor.data.index(finfo) widgeteditor._refresh_outlineexplorer(index, update=True) self.emit(SIGNAL('ending_long_process(QString)'), "") if widgeteditor.isVisible() and widgeteditor.checkeolchars_enabled \ and sourcecode.has_mixed_eol_chars(text): name = os.path.basename(pythonfile) QMessageBox.warning(self, widgeteditor.title, _("<b>%s</b> contains mixed end-of-line " "characters.<br>Spyder will fix this " "automatically.") % name, QMessageBox.Ok) widgeteditor.set_os_eol_chars(index) widgeteditor.is_analysis_done = False finfo.editor.set_cursor_position('eof') finfo.editor.insert_text(os.linesep) return finfo, sedmlfile
def _set_step(self, step): """Proceed to a given step""" new_tab = self.tab_widget.currentIndex() + step assert new_tab < self.tab_widget.count() and new_tab >= 0 if new_tab == self.tab_widget.count() - 1: try: self.table_widget.open_data( self._get_plain_text(), self.text_widget.get_col_sep(), self.text_widget.get_row_sep(), self.text_widget.trnsp_box.isChecked(), self.text_widget.get_skiprows(), self.text_widget.get_comments()) self.done_btn.setEnabled(True) self.done_btn.setDefault(True) self.fwd_btn.setEnabled(False) self.back_btn.setEnabled(True) except (SyntaxError, AssertionError) as error: QMessageBox.critical( self, _("Import wizard"), _("<b>Unable to proceed to next step</b>" "<br><br>Please check your entries." "<br><br>Error message:<br>%s") % str(error)) return elif new_tab == 0: self.done_btn.setEnabled(False) self.fwd_btn.setEnabled(True) self.back_btn.setEnabled(False) self._focus_tab(new_tab)
def start(self): filename = to_text_string(self.filecombo.currentText()) self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.SeparateChannels) self.process.setWorkingDirectory(osp.dirname(filename)) self.process.readyReadStandardOutput.connect(self.read_output) self.process.readyReadStandardError.connect( lambda: self.read_output(error=True)) self.process.finished.connect(lambda ec, es=QProcess.ExitStatus: self.finished(ec, es)) self.stop_button.clicked.connect(self.process.kill) self.output = '' self.error_output = '' plver = PYLINT_VER if plver is not None: if plver.split('.')[0] == '0': p_args = ['-i', 'yes'] else: # Option '-i' (alias for '--include-ids') was removed in pylint # 1.0 p_args = ["--msg-template='{msg_id}:{line:3d},"\ "{column}: {obj}: {msg}"] p_args += [osp.basename(filename)] else: p_args = [osp.basename(filename)] self.process.start(PYLINT_PATH, p_args) running = self.process.waitForStarted() self.set_running_state(running) if not running: QMessageBox.critical(self, _("Error"), _("Process failed to start"))
def save_data(self, filename=None): """Save data""" if filename is None: filename = self.filename if filename is None: filename = getcwd() filename, _selfilter = getsavefilename(self, _("Save data"), filename, iofunctions.save_filters) if filename: self.filename = filename else: return False QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() if self.is_internal_shell: wsfilter = self.get_internal_shell_filter('picklable', check_all=True) namespace = wsfilter(self.shellwidget.interpreter.namespace).copy() error_message = iofunctions.save(namespace, filename) else: settings = self.get_view_settings() error_message = monitor_save_globals(self._get_sock(), settings, filename) QApplication.restoreOverrideCursor() QApplication.processEvents() if error_message is not None: QMessageBox.critical(self, _("Save data"), _("<b>Unable to save current workspace</b>" "<br><br>Error message:<br>%s") % error_message) self.save_button.setEnabled(self.filename is not None)
def chdir(self, directory=None, browsing_history=False): """Set directory as working directory""" if directory is not None: directory = osp.abspath(to_text_string(directory)) if browsing_history: directory = self.history[self.histindex] elif directory in self.history: self.histindex = self.history.index(directory) else: if self.histindex is None: self.history = [] else: self.history = self.history[: self.histindex + 1] if len(self.history) == 0 or (self.history and self.history[-1] != directory): self.history.append(directory) self.histindex = len(self.history) - 1 directory = to_text_string(directory) if PY2: PermissionError = OSError try: os.chdir(directory) self.parent_widget.open_dir.emit(directory) self.refresh(new_path=directory, force_current=True) except PermissionError: QMessageBox.critical( self.parent_widget, "Error", _("You don't have the right permissions to " "open this directory") )
def load_and_translate(self, combine, pythonfile, editor, set_current=True): """ Read filename as combine archive, unzip, translate, reconstitute in Python, and create an editor instance and return it *Warning* This is loading file, creating editor but not executing the source code analysis -- the analysis must be done by the editor plugin (in case multiple editorstack instances are handled) """ combine = str(combine) self.emit(SIGNAL('starting_long_process(QString)'), _("Loading %s...") % combine) text, enc = encoding.read(combine) text = Translatecombine(combine) zipextloctemp, sbmlloclisttemp, sedmlloclisttemp = manifestsearch(combine) for i in range(len(text)): widgeteditor = editor.editorstacks[0] sedmlfname = os.path.basename(sedmlloclisttemp[i]) finfo = widgeteditor.create_new_editor(os.path.splitext(sedmlfname)[0] + '_phrasedml.py', enc, text[i], set_current, new=True) index = widgeteditor.data.index(finfo) widgeteditor._refresh_outlineexplorer(index, update=True) self.emit(SIGNAL('ending_long_process(QString)'), "") if widgeteditor.isVisible() and widgeteditor.checkeolchars_enabled \ and sourcecode.has_mixed_eol_chars(text[i]): name = os.path.basename(pythonfile[:-3] + '_phrasedml.py') QMessageBox.warning(self, widgeteditor.title, _("<b>%s</b> contains mixed end-of-line " "characters.<br>Spyder will fix this " "automatically.") % name, QMessageBox.Ok) widgeteditor.set_os_eol_chars(index) widgeteditor.is_analysis_done = False finfo.editor.set_cursor_position('eof') finfo.editor.insert_text(os.linesep) return finfo, combine
def set_user_env(reg, parent=None): """Set HKCU (current user) environment variables""" reg = listdict2envdict(reg) types = dict() key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") for name in reg: try: _x, types[name] = winreg.QueryValueEx(key, name) except WindowsError: types[name] = winreg.REG_EXPAND_SZ key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_SET_VALUE) for name in reg: winreg.SetValueEx(key, name, 0, types[name], reg[name]) try: from win32gui import SendMessageTimeout from win32con import (HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG) SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", SMTO_ABORTIFHUNG, 5000) except ImportError: QMessageBox.warning(parent, _("Warning"), _("Module <b>pywin32 was not found</b>.<br>" "Please restart this Windows <i>session</i> " "(not the computer) for changes to take effect."))
def rename_file(self, fname): """Rename file""" path, valid = QInputDialog.getText(self, _('Rename'), _('New name:'), QLineEdit.Normal, osp.basename(fname)) if valid: path = osp.join(osp.dirname(fname), to_text_string(path)) if path == fname: return if osp.exists(path): if QMessageBox.warning(self, _("Rename"), _("Do you really want to rename <b>%s</b> and " "overwrite the existing file <b>%s</b>?" ) % (osp.basename(fname), osp.basename(path)), QMessageBox.Yes|QMessageBox.No) == QMessageBox.No: return try: misc.rename_file(fname, path) self.parent_widget.emit( \ SIGNAL("renamed(QString,QString)"), fname, path) return path except EnvironmentError as error: QMessageBox.critical(self, _("Rename"), _("<b>Unable to rename file <i>%s</i></b>" "<br><br>Error message:<br>%s" ) % (osp.basename(fname), to_text_string(error)))
def create_new_folder(self, current_path, title, subtitle, is_package): """Create new folder""" if current_path is None: current_path = "" if osp.isfile(current_path): current_path = osp.dirname(current_path) name, valid = QInputDialog.getText(self, title, subtitle, QLineEdit.Normal, "") if valid: dirname = osp.join(current_path, to_text_string(name)) try: os.mkdir(dirname) except EnvironmentError as error: QMessageBox.critical( self, title, _("<b>Unable " "to create folder <i>%s</i></b>" "<br><br>Error message:<br>%s") % (dirname, to_text_string(error)), ) finally: if is_package: fname = osp.join(dirname, "__init__.py") try: with open(fname, "wb") as f: f.write(to_binary_string("#")) return dirname except EnvironmentError as error: QMessageBox.critical( self, title, _("<b>Unable " "to create file <i>%s</i></b>" "<br><br>Error message:<br>%s") % (fname, to_text_string(error)), )
def start(self): filename = to_text_string(self.filecombo.currentText()) self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.SeparateChannels) self.process.setWorkingDirectory(osp.dirname(filename)) self.process.readyReadStandardOutput.connect(self.read_output) self.process.readyReadStandardError.connect( lambda: self.read_output(error=True)) self.process.finished.connect( lambda ec, es=QProcess.ExitStatus: self.finished(ec, es)) self.stop_button.clicked.connect(self.process.kill) self.output = '' self.error_output = '' plver = PYLINT_VER if plver is not None: if plver.split('.')[0] == '0': p_args = ['-i', 'yes'] else: # Option '-i' (alias for '--include-ids') was removed in pylint # 1.0 p_args = ["--msg-template='{msg_id}:{line:3d},"\ "{column}: {obj}: {msg}"] p_args += [osp.basename(filename)] else: p_args = [osp.basename(filename)] self.process.start(PYLINT_PATH, p_args) running = self.process.waitForStarted() self.set_running_state(running) if not running: QMessageBox.critical(self, _("Error"), _("Process failed to start"))
def create_new_folder(self, current_path, title, subtitle, is_package): """Create new folder""" if current_path is None: current_path = '' if osp.isfile(current_path): current_path = osp.dirname(current_path) name, valid = QInputDialog.getText(self, title, subtitle, QLineEdit.Normal, "") if valid: dirname = osp.join(current_path, to_text_string(name)) try: os.mkdir(dirname) except EnvironmentError as error: QMessageBox.critical(self, title, _("<b>Unable " "to create folder <i>%s</i></b>" "<br><br>Error message:<br>%s" ) % (dirname, to_text_string(error))) finally: if is_package: fname = osp.join(dirname, '__init__.py') try: with open(fname, 'wb') as f: f.write(to_binary_string('#')) return dirname except EnvironmentError as error: QMessageBox.critical(self, title, _("<b>Unable " "to create file <i>%s</i></b>" "<br><br>Error message:<br>%s" ) % (fname, to_text_string(error)))
def delete_file(self, fname, multiple, yes_to_all): """Delete file""" if multiple: buttons = QMessageBox.Yes | QMessageBox.YesAll | QMessageBox.No | QMessageBox.Cancel else: buttons = QMessageBox.Yes | QMessageBox.No if yes_to_all is None: answer = QMessageBox.warning( self, _("Delete"), _("Do you really want " "to delete <b>%s</b>?") % osp.basename(fname), buttons ) if answer == QMessageBox.No: return yes_to_all elif answer == QMessageBox.Cancel: return False elif answer == QMessageBox.YesAll: yes_to_all = True try: if osp.isfile(fname): misc.remove_file(fname) self.parent_widget.removed.emit(fname) else: self.remove_tree(fname) self.parent_widget.removed_tree.emit(fname) return yes_to_all except EnvironmentError as error: action_str = _("delete") QMessageBox.critical( self, _("Project Explorer"), _("<b>Unable to %s <i>%s</i></b>" "<br><br>Error message:<br>%s") % (action_str, fname, to_text_string(error)), ) return False
def delete_file(self, fname, multiple, yes_to_all): """Delete file""" if multiple: buttons = QMessageBox.Yes|QMessageBox.YesAll| \ QMessageBox.No|QMessageBox.Cancel else: buttons = QMessageBox.Yes|QMessageBox.No if yes_to_all is None: answer = QMessageBox.warning(self, _("Delete"), _("Do you really want " "to delete <b>%s</b>?" ) % osp.basename(fname), buttons) if answer == QMessageBox.No: return yes_to_all elif answer == QMessageBox.Cancel: return False elif answer == QMessageBox.YesAll: yes_to_all = True try: if osp.isfile(fname): misc.remove_file(fname) self.parent_widget.emit(SIGNAL("removed(QString)"), fname) else: self.remove_tree(fname) self.parent_widget.emit(SIGNAL("removed_tree(QString)"), fname) return yes_to_all except EnvironmentError as error: action_str = _('delete') QMessageBox.critical(self, _("Project Explorer"), _("<b>Unable to %s <i>%s</i></b>" "<br><br>Error message:<br>%s" ) % (action_str, fname, to_text_string(error))) return False
def finished(self, exit_code, exit_status): self.set_running_state(False) if not self.output: if self.error_output: QMessageBox.critical(self, _("Error"), self.error_output) print("pylint error:\n\n" + self.error_output, file=sys.stderr) return # Convention, Refactor, Warning, Error results = {'C:': [], 'R:': [], 'W:': [], 'E:': []} txt_module = '************* Module ' module = '' # Should not be needed - just in case something goes wrong for line in self.output.splitlines(): if line.startswith(txt_module): # New module module = line[len(txt_module):] continue # Supporting option include-ids: ('R3873:' instead of 'R:') if not re.match('^[CRWE]+([0-9]{4})?:', line): continue i1 = line.find(':') if i1 == -1: continue msg_id = line[:i1] i2 = line.find(':', i1+1) if i2 == -1: continue line_nb = line[i1+1:i2].strip() if not line_nb: continue line_nb = int(line_nb.split(',')[0]) message = line[i2+1:] item = (module, line_nb, message, msg_id) results[line[0]+':'].append(item) # Rate rate = None txt_rate = 'Your code has been rated at ' i_rate = self.output.find(txt_rate) if i_rate > 0: i_rate_end = self.output.find('/10', i_rate) if i_rate_end > 0: rate = self.output[i_rate+len(txt_rate):i_rate_end] # Previous run previous = '' if rate is not None: txt_prun = 'previous run: ' i_prun = self.output.find(txt_prun, i_rate_end) if i_prun > 0: i_prun_end = self.output.find('/10', i_prun) previous = self.output[i_prun+len(txt_prun):i_prun_end] filename = to_text_string(self.filecombo.currentText()) self.set_data(filename, (time.localtime(), rate, previous, results)) self.output = self.error_output + self.output self.show_data(justanalyzed=True)
def finished(self): self.set_running_state(False) if not self.output: if self.error_output: QMessageBox.critical(self, _("Error"), self.error_output) print("pylint error:\n\n" + self.error_output, file=sys.stderr) return # Convention, Refactor, Warning, Error results = {'C:': [], 'R:': [], 'W:': [], 'E:': []} txt_module = '************* Module ' module = '' # Should not be needed - just in case something goes wrong for line in self.output.splitlines(): if line.startswith(txt_module): # New module module = line[len(txt_module):] continue # Supporting option include-ids: ('R3873:' instead of 'R:') if not re.match('^[CRWE]+([0-9]{4})?:', line): continue i1 = line.find(':') if i1 == -1: continue msg_id = line[:i1] i2 = line.find(':', i1+1) if i2 == -1: continue line_nb = line[i1+1:i2].strip() if not line_nb: continue line_nb = int(line_nb.split(',')[0]) message = line[i2+1:] item = (module, line_nb, message, msg_id) results[line[0]+':'].append(item) # Rate rate = None txt_rate = 'Your code has been rated at ' i_rate = self.output.find(txt_rate) if i_rate > 0: i_rate_end = self.output.find('/10', i_rate) if i_rate_end > 0: rate = self.output[i_rate+len(txt_rate):i_rate_end] # Previous run previous = '' if rate is not None: txt_prun = 'previous run: ' i_prun = self.output.find(txt_prun, i_rate_end) if i_prun > 0: i_prun_end = self.output.find('/10', i_prun) previous = self.output[i_prun+len(txt_prun):i_prun_end] filename = to_text_string(self.filecombo.currentText()) self.set_data(filename, (time.localtime(), rate, previous, results)) self.output = self.error_output + self.output self.show_data(justanalyzed=True)
def restart_message(self): """ Print a restart message when the client is connected to an external kernel """ message = _("Kernel process is either remote or unspecified. " "Cannot restart.") QMessageBox.information(self, "IPython", message)
def show_message(is_checked): if is_checked or not msg_if_enabled: if msg_warning is not None: QMessageBox.warning(self, self.get_name(), msg_warning, QMessageBox.Ok) if msg_info is not None: QMessageBox.information(self, self.get_name(), msg_info, QMessageBox.Ok)
def is_valid(self): wdir = to_text_string(self.wd_edit.text()) if not self.wd_cb.isChecked() or osp.isdir(wdir): return True else: QMessageBox.critical(self, _("Run configuration"), _("The following working directory is " "not valid:<br><b>%s</b>") % wdir) return False
def scm_command(self, fnames, tool): """SCM command (Mercurial, git...)""" try: for path in sorted(fnames): scm.run_scm_tool(path, tool=tool) except RuntimeError, error: QMessageBox.critical(self, _("Error"), _("<b>Unable to find external program.</b>" "<br><br>%s") % unicode(error))
def _on_sphinx_thread_error_msg(self, error_msg): """ Display error message on Sphinx rich text failure""" self.plain_text_action.setChecked(True) QMessageBox.critical( self, _('Object inspector'), _("The following error occured when calling " "<b>Sphinx %s</b>. <br>Incompatible Sphinx " "version or doc string decoding failed." "<br><br>Error message:<br>%s") % (sphinx_version, error_msg))
def _create_client_for_kernel(self, cf, hostname, kf, pw): # Verifying if the connection file exists - in the case of an empty # file name, the last used connection file is returned. try: cf = find_connection_file(cf, profile='default') except (IOError, UnboundLocalError): QMessageBox.critical(self, _('IPython'), _("Unable to connect to IPython <b>%s") % cf) return # Base client name: # remove path and extension, and use the last part when split by '-' base_client_name = osp.splitext(cf.split('/')[-1])[0].split('-')[-1] # Generating the client name by appending /A, /B... until it is unique count = 0 while True: client_name = base_client_name + '/' + chr(65 + count) for cl in self.get_clients(): if cl.name == client_name: break else: break count += 1 # Getting kernel_widget_id from the currently open kernels. kernel_widget_id = None for sw in self.extconsole.shellwidgets: if sw.connection_file == cf.split('/')[-1]: kernel_widget_id = id(sw) # Verifying if frontend and kernel have compatible versions if not self.kernel_and_frontend_match(cf): QMessageBox.critical( self, _("Mismatch between kernel and frontend"), _("Your IPython frontend and kernel versions " "are <b>incompatible!!</b>" "<br><br>" "We're sorry but we can't create an IPython " "console for you."), QMessageBox.Ok) return # Creating the client client = IPythonClient(self, history_filename='history.py', connection_file=cf, kernel_widget_id=kernel_widget_id, menu_actions=self.menu_actions, hostname=hostname, sshkey=kf, password=pw) # Adding the tab self.add_tab(client, name=client.get_name()) # Connecting kernel and client self.register_client(client, client_name)
def _on_sphinx_thread_error_msg(self, error_msg): """ Display error message on Sphinx rich text failure""" self.plain_text_action.setChecked(True) QMessageBox.critical(self, _('Object inspector'), _("The following error occured when calling " "<b>Sphinx %s</b>. <br>Incompatible Sphinx " "version or doc string decoding failed." "<br><br>Error message:<br>%s" ) % (sphinx_version, error_msg))
def run_python_script_in_terminal(fname, wdir, args, interact, debug, python_args): """Run Python script in an external system terminal""" # If fname has spaces on it it can't be ran on Windows, so we have to # enclose it in quotes. Also wdir can come with / as os.sep, so we # need to take care of it if os.name == 'nt': fname = '"' + fname + '"' wdir = wdir.replace('/', '\\') p_args = ['python'] p_args += get_python_args(fname, python_args, interact, debug, args) if os.name == 'nt': cmd = 'start cmd.exe /c "cd %s && ' % wdir + ' '.join(p_args) + '"' # Command line and cwd have to be converted to the filesystem # encoding before passing them to subprocess, but only for # Python 2. # See http://bugs.python.org/issue1759845#msg74142 and Issue 1856 if PY2: cmd = encoding.to_fs_from_unicode(cmd) wdir = encoding.to_fs_from_unicode(wdir) try: subprocess.Popen(cmd, shell=True, cwd=wdir) except WindowsError: from spyderlib.qt.QtGui import QMessageBox from spyderlib.baseconfig import _ QMessageBox.critical(None, _('Run'), _("It was not possible to run this file in " "an external terminal"), QMessageBox.Ok) elif os.name == 'posix': cmd = 'gnome-terminal' if is_program_installed(cmd): run_program(cmd, ['--working-directory', wdir, '-x'] + p_args, cwd=wdir) return cmd = 'konsole' if is_program_installed(cmd): run_program(cmd, ['--workdir', wdir, '-e'] + p_args, cwd=wdir) return cmd = 'xfce4-terminal' if is_program_installed(cmd): run_program(cmd, ['--working-directory', wdir, '-x'] + p_args, cwd=wdir) return cmd = 'xterm' if is_program_installed(cmd): run_program(cmd, ['-e'] + p_args + [wdir]) return # TODO: Add a fallback to OSX else: raise NotImplementedError
def _create_client_for_kernel(self, cf, hostname, kf, pw): # Verifying if the connection file exists - in the case of an empty # file name, the last used connection file is returned. try: cf = find_connection_file(cf, profile='default') except (IOError, UnboundLocalError): QMessageBox.critical(self, _('IPython'), _("Unable to connect to IPython <b>%s") % cf) return # Base client name: # remove path and extension, and use the last part when split by '-' base_client_name = osp.splitext(cf.split('/')[-1])[0].split('-')[-1] # Generating the client name by appending /A, /B... until it is unique count = 0 while True: client_name = base_client_name + '/' + chr(65 + count) for cl in self.get_clients(): if cl.name == client_name: break else: break count += 1 # Getting kernel_widget_id from the currently open kernels. kernel_widget_id = None for sw in self.extconsole.shellwidgets: if sw.connection_file == cf.split('/')[-1]: kernel_widget_id = id(sw) # Verifying if frontend and kernel have compatible versions if not self.kernel_and_frontend_match(cf): QMessageBox.critical(self, _("Mismatch between kernel and frontend"), _("Your IPython frontend and kernel versions " "are <b>incompatible!!</b>" "<br><br>" "We're sorry but we can't create an IPython " "console for you." ), QMessageBox.Ok) return # Creating the client client = IPythonClient(self, history_filename='history.py', connection_file=cf, kernel_widget_id=kernel_widget_id, menu_actions=self.menu_actions, hostname=hostname, sshkey=kf, password=pw) # Adding the tab self.add_tab(client, name=client.get_name()) # Connecting kernel and client self.register_client(client, client_name)
def _on_sphinx_thread_error_msg(self, error_msg): """ Display error message on Sphinx rich text failure""" self._sphinx_thread.wait() self.plain_text_action.setChecked(True) sphinx_ver = programs.get_module_version('sphinx') QMessageBox.critical( self, _('Help'), _("The following error occured when calling " "<b>Sphinx %s</b>. <br>Incompatible Sphinx " "version or doc string decoding failed." "<br><br>Error message:<br>%s") % (sphinx_ver, error_msg))
def create_process(self): self.shell.clear() self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.MergedChannels) # PYTHONPATH (in case we use Python in this terminal, e.g. py2exe) env = [ to_text_string(_path) for _path in self.process.systemEnvironment() ] processEnvironment = QProcessEnvironment() for envItem in env: envName, separator, envValue = envItem.partition('=') processEnvironment.insert(envName, envValue) add_pathlist_to_PYTHONPATH(env, self.path) self.process.setProcessEnvironment(processEnvironment) # Working directory if self.wdir is not None: self.process.setWorkingDirectory(self.wdir) # Shell arguments if os.name == 'nt': p_args = ['/Q'] else: p_args = ['-i'] if self.arguments: p_args.extend(shell_split(self.arguments)) self.process.readyReadStandardOutput.connect(self.write_output) self.process.finished.connect(self.finished) self.kill_button.clicked.connect(self.process.kill) if os.name == 'nt': self.process.start('cmd.exe', p_args) else: # Using bash: self.process.start('bash', p_args) self.send_to_process('PS1="\\u@\\h:\\w> "\n') running = self.process.waitForStarted() self.set_running_state(running) if not running: QMessageBox.critical(self, _("Error"), _("Process failed to start")) else: self.shell.setFocus() self.started.emit() return self.process
def convert_notebook(self, fname): """Convert an IPython notebook to a Python script in editor""" try: script = nbexporter().from_filename(fname)[0] except Exception as e: QMessageBox.critical(self, _('Conversion error'), _("It was not possible to convert this " "notebook. The error is:\n\n") + \ to_text_string(e)) return self.parent_widget.sig_new_file.emit(script)
def create_kernel_manager_and_client(self, connection_file=None, hostname=None, sshkey=None, password=None): """Create kernel manager and client""" cf = find_connection_file(connection_file, profile='default') kernel_manager = QtKernelManager(connection_file=cf, config=None) if programs.is_module_installed('IPython', '>=1.0'): kernel_client = kernel_manager.client() kernel_client.load_connection_file() if hostname is not None: try: newports = tunnel_to_kernel( dict(ip=kernel_client.ip, shell_port=kernel_client.shell_port, iopub_port=kernel_client.iopub_port, stdin_port=kernel_client.stdin_port, hb_port=kernel_client.hb_port), hostname, sshkey, password) (kernel_client.shell_port, kernel_client.iopub_port, kernel_client.stdin_port, kernel_client.hb_port) = newports except Exception as e: QMessageBox.critical( self, _('Connection error'), _('Could not open ssh tunnel\n') + str(e)) return None, None kernel_client.start_channels() # To rely on kernel's heartbeat to know when a kernel has died kernel_client.hb_channel.unpause() return kernel_manager, kernel_client else: kernel_manager.load_connection_file() if hostname is not None: try: newports = tunnel_to_kernel( dict(ip=kernel_manager.ip, shell_port=kernel_manager.shell_port, iopub_port=kernel_manager.iopub_port, stdin_port=kernel_manager.stdin_port, hb_port=kernel_manager.hb_port), hostname, sshkey, password) (kernel_manager.shell_port, kernel_manager.iopub_port, kernel_manager.stdin_port, kernel_manager.hb_port) = newports except Exception as e: QMessageBox.critical( self, _('Connection error'), _('Could not open ssh tunnel\n') + str(e)) return None, None kernel_manager.start_channels() return kernel_manager, None
def is_valid(self): """Return True if all widget contents are valid""" for lineedit in self.lineedits: if lineedit in self.validate_data and lineedit.isEnabled(): validator, invalid_msg = self.validate_data[lineedit] text = to_text_string(lineedit.text()) if not validator(text): QMessageBox.critical(self, self.get_name(), "%s:<br><b>%s</b>" % (invalid_msg, text), QMessageBox.Ok) return False return True
def vcs_command(self, fnames, action): """VCS action (commit, browse)""" try: for path in sorted(fnames): vcs.run_vcs_tool(path, action) except vcs.ActionToolNotFound as error: msg = _("For %s support, please install one of the<br/> " "following tools:<br/><br/> %s")\ % (error.vcsname, ', '.join(error.tools)) QMessageBox.critical(self, _("Error"), _("""<b>Unable to find external program.</b><br><br>%s""") % to_text_string(msg))
def change_format(self): """Change display format""" format, valid = QInputDialog.getText(self, _( 'Format'), _( "Float formatting"), QLineEdit.Normal, self.model.get_format()) if valid: format = str(format) try: format % 1.1 except: QMessageBox.critical(self, _("Error"), _("Format (%s) is incorrect") % format) return self.model.set_format(format)