def select_directory(self): """Select directory""" self.redirect_stdio.emit(False) directory = getexistingdirectory(self.main, _("Select directory"), getcwd()) if directory: self.chdir(directory) self.redirect_stdio.emit(True)
def __init__(self, parent=None, name_filters=['*.py', '*.pyw'], valid_types=('.py', '.pyw'), show_all=False, show_cd_only=None, show_toolbar=True, show_icontext=True): QWidget.__init__(self, parent) self.treewidget = ExplorerTreeWidget(self, show_cd_only=show_cd_only) self.treewidget.setup(name_filters=name_filters, valid_types=valid_types, show_all=show_all) self.treewidget.chdir(getcwd()) toolbar_action = create_action(self, _("Show toolbar"), toggled=self.toggle_toolbar) icontext_action = create_action(self, _("Show icons and text"), toggled=self.toggle_icontext) self.treewidget.common_actions += [None, toolbar_action, icontext_action] # Setup toolbar self.toolbar = QToolBar(self) self.toolbar.setIconSize(QSize(16, 16)) self.previous_action = create_action(self, text=_("Previous"), icon=get_icon('previous.png'), triggered=self.treewidget.go_to_previous_directory) self.toolbar.addAction(self.previous_action) self.previous_action.setEnabled(False) self.connect(self.treewidget, SIGNAL("set_previous_enabled(bool)"), self.previous_action.setEnabled) self.next_action = create_action(self, text=_("Next"), icon=get_icon('next.png'), triggered=self.treewidget.go_to_next_directory) self.toolbar.addAction(self.next_action) self.next_action.setEnabled(False) self.connect(self.treewidget, SIGNAL("set_next_enabled(bool)"), self.next_action.setEnabled) parent_action = create_action(self, text=_("Parent"), icon=get_icon('up.png'), triggered=self.treewidget.go_to_parent_directory) self.toolbar.addAction(parent_action) options_action = create_action(self, text='', tip=_("Options"), icon=get_icon('tooloptions.png')) self.toolbar.addAction(options_action) widget = self.toolbar.widgetForAction(options_action) widget.setPopupMode(QToolButton.InstantPopup) menu = QMenu(self) add_actions(menu, self.treewidget.common_actions) options_action.setMenu(menu) toolbar_action.setChecked(show_toolbar) self.toggle_toolbar(show_toolbar) icontext_action.setChecked(show_icontext) self.toggle_icontext(show_icontext) vlayout = QVBoxLayout() vlayout.addWidget(self.toolbar) vlayout.addWidget(self.treewidget) self.setLayout(vlayout)
def refresh_plugin(self): """Refresh widget""" curdir = getcwd() self.pathedit.add_text(curdir) self.save_wdhistory() self.set_previous_enabled.emit(self.histindex is not None and self.histindex > 0) self.set_next_enabled.emit(self.histindex is not None and self.histindex < len(self.history) - 1)
def compare(self): filename, _selfilter = getopenfilename(self, _("Select script to compare"), getcwd(), _("Profiler result")+" (*.Result)") if filename: self.datatree.compare(filename) self.show_data() self.clear_button.setEnabled(True)
def select_file(self): self.redirect_stdio.emit(False) filename, _selfilter = getopenfilename(self, _("Select Python script"), getcwd(), _("Python scripts")+" (*.py ; *.pyw)") self.redirect_stdio.emit(True) if filename: self.analyze(filename)
def run_script(self, filename=None, silent=False, set_focus=False, args=None): """Run a Python script""" if filename is None: self.shell.interpreter.restore_stds() filename, _selfilter = getopenfilename( self, _("Run Python script"), getcwd(), _("Python scripts") + " (*.py ; *.pyw ; *.ipy)") self.shell.interpreter.redirect_stds() if filename: os.chdir(osp.dirname(filename)) filename = osp.basename(filename) else: return filename = osp.abspath(filename) rbs = remove_backslashes command = "runfile('%s', args='%s')" % (rbs(filename), rbs(args)) if set_focus: self.shell.setFocus() if self.dockwidget and not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.raise_() self.shell.write(command + '\n') self.shell.run_command(command)
def detect_hg_repository(self, path=None): if path is None: path = getcwd() hg_repository = is_hg_installed() and get_vcs_root(path) is not None self.hg_manifest.setEnabled(hg_repository) if not hg_repository and self.hg_manifest.isChecked(): self.custom_dir.setChecked(True)
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 select_file(self): self.emit(SIGNAL('redirect_stdio(bool)'), False) filename, _selfilter = getopenfilename(self, _("Select Python file"), getcwd(), _("Python files")+" (*.py ; *.pyw)") self.emit(SIGNAL('redirect_stdio(bool)'), False) if filename: self.analyze(filename)
def set(self, options): self.args = options.get("args", "") self.args_enabled = options.get("args/enabled", False) if CONF.get("run", WDIR_USE_FIXED_DIR_OPTION, False): default_wdir = CONF.get("run", WDIR_FIXED_DIR_OPTION, getcwd()) self.wdir = options.get("workdir", default_wdir) self.wdir_enabled = True else: self.wdir = options.get("workdir", getcwd()) self.wdir_enabled = options.get("workdir/enabled", False) self.current = options.get("current", CONF.get("run", CURRENT_INTERPRETER_OPTION, True)) self.systerm = options.get("systerm", CONF.get("run", SYSTERM_INTERPRETER_OPTION, False)) self.interact = options.get("interact", CONF.get("run", "interact", False)) self.show_kill_warning = options.get("show_kill_warning", CONF.get("run", "show_kill_warning", False)) self.post_mortem = options.get("post_mortem", CONF.get("run", "post_mortem", False)) self.python_args = options.get("python_args", "") self.python_args_enabled = options.get("python_args/enabled", False)
def save_data(self): """Save data""" title = _( "Save profiler result") filename, _selfilter = getsavefilename(self, title, getcwd(), _("Profiler result")+" (*.Result)") if filename: self.datatree.save_data(filename)
def save_data(self): """Save data""" title = _("Save profiler result") filename, _selfilter = getsavefilename( self, title, getcwd(), _("Profiler result") + " (*.Result)") if filename: self.datatree.save_data(filename)
def select_directory(self): """Select directory""" self.emit(SIGNAL('redirect_stdio(bool)'), False) directory = getexistingdirectory(self.main, _("Select directory"), getcwd()) if directory: self.chdir(directory) self.emit(SIGNAL('redirect_stdio(bool)'), True)
def select_directory(self, edit): """Select directory""" basedir = to_text_string(edit.text()) if not osp.isdir(basedir): basedir = getcwd() title = _("Select directory") directory = getexistingdirectory(self, title, basedir) if directory: edit.setText(directory)
def select_directory(self): """Select directory""" basedir = to_text_string(self.wd_edit.text()) if not osp.isdir(basedir): basedir = getcwd() directory = getexistingdirectory(self, _("Select directory"), basedir) if directory: self.wd_edit.setText(directory) self.wd_cb.setChecked(True)
def refresh_plugin(self): """Refresh widget""" curdir = getcwd() self.pathedit.add_text(curdir) self.save_wdhistory() self.set_previous_enabled.emit(self.histindex is not None and self.histindex > 0) self.set_next_enabled.emit(self.histindex is not None and \ self.histindex < len(self.history)-1)
def set(self, options): self.args = options.get('args', '') self.args_enabled = options.get('args/enabled', False) if CONF.get('run', WDIR_USE_FIXED_DIR_OPTION, False): default_wdir = CONF.get('run', WDIR_FIXED_DIR_OPTION, getcwd()) self.wdir = options.get('workdir', default_wdir) self.wdir_enabled = True else: self.wdir = options.get('workdir', getcwd()) self.wdir_enabled = options.get('workdir/enabled', False) self.current = options.get('current', CONF.get('run', CURRENT_INTERPRETER_OPTION, True)) self.systerm = options.get('systerm', CONF.get('run', SYSTERM_INTERPRETER_OPTION, False)) self.interact = options.get('interact', False) self.show_kill_warning = options.get('show_kill_warning', True) self.python_args = options.get('python_args', '') self.python_args_enabled = options.get('python_args/enabled', False)
def load_wdhistory(self, workdir=None): """Load history from a text file in user home directory""" if osp.isfile(self.LOG_PATH): wdhistory, _ = encoding.readlines(self.LOG_PATH) wdhistory = [name for name in wdhistory if os.path.isdir(name)] else: if workdir is None: workdir = getcwd() wdhistory = [ workdir ] return wdhistory
def load_wdhistory(self, workdir=None): """Load history from a text file in user home directory""" if osp.isfile(self.LOG_PATH): wdhistory, _ = encoding.readlines(self.LOG_PATH) wdhistory = [name for name in wdhistory if os.path.isdir(name)] else: if workdir is None: workdir = getcwd() wdhistory = [workdir] return wdhistory
def select_file(self, edit, filters=None): """Select File""" basedir = osp.dirname(to_text_string(edit.text())) if not osp.isdir(basedir): basedir = getcwd() if filters is None: filters = _("All files (*)") title = _("Select file") filename, _selfilter = getopenfilename(self, title, basedir, filters) if filename: edit.setText(filename)
def refresh(self, new_path=None, force_current=False): """Refresh widget force=False: won't refresh widget if path has not changed""" if new_path is None: new_path = getcwd() if force_current: index = self.set_current_folder(new_path) self.expand(index) self.setCurrentIndex(index) self.set_previous_enabled.emit(self.histindex is not None and self.histindex > 0) self.set_next_enabled.emit(self.histindex is not None and self.histindex < len(self.history) - 1)
def get_pythonxy_plugindir(name): """Searching Python(x,y) plugin directory in current working directory""" for fname in os.listdir(getcwd()): path = osp.abspath(osp.join(fname, 'src', 'python', name)) if osp.isdir(path): # Also create the binary directory if it does not exist yet: def create_dir(path): if not osp.isdir(path): os.mkdir(path) create_dir(osp.join(fname, 'bin')) create_dir(osp.join(fname, 'bin', 'python')) return path
def __init__(self, parent=None, name_filters=['*.py', '*.pyw'], show_all=False, show_cd_only=None, show_icontext=True): QWidget.__init__(self, parent) self.treewidget = ExplorerTreeWidget(self, show_cd_only=show_cd_only) self.treewidget.setup(name_filters=name_filters, show_all=show_all) self.treewidget.chdir(getcwd()) icontext_action = create_action(self, _("Show icons and text"), toggled=self.toggle_icontext) self.treewidget.common_actions += [None, icontext_action] # Setup toolbar self.toolbar = QToolBar(self) self.toolbar.setIconSize(QSize(16, 16)) self.previous_action = create_action(self, text=_("Previous"), icon=ima.icon('ArrowBack'), triggered=self.treewidget.go_to_previous_directory) self.toolbar.addAction(self.previous_action) self.previous_action.setEnabled(False) self.treewidget.set_previous_enabled.connect( self.previous_action.setEnabled) self.next_action = create_action(self, text=_("Next"), icon=ima.icon('ArrowForward'), triggered=self.treewidget.go_to_next_directory) self.toolbar.addAction(self.next_action) self.next_action.setEnabled(False) self.treewidget.set_next_enabled.connect(self.next_action.setEnabled) parent_action = create_action(self, text=_("Parent"), icon=ima.icon('ArrowUp'), triggered=self.treewidget.go_to_parent_directory) self.toolbar.addAction(parent_action) self.toolbar.addSeparator() options_action = create_action(self, text='', tip=_('Options'), icon=ima.icon('tooloptions')) self.toolbar.addAction(options_action) widget = self.toolbar.widgetForAction(options_action) widget.setPopupMode(QToolButton.InstantPopup) menu = QMenu(self) add_actions(menu, self.treewidget.common_actions) options_action.setMenu(menu) icontext_action.setChecked(show_icontext) self.toggle_icontext(show_icontext) vlayout = QVBoxLayout() vlayout.addWidget(self.toolbar) vlayout.addWidget(self.treewidget) self.setLayout(vlayout)
def refresh(self, new_path=None, force_current=False): """Refresh widget force=False: won't refresh widget if path has not changed""" if new_path is None: new_path = getcwd() if force_current: index = self.set_current_folder(new_path) self.expand(index) self.setCurrentIndex(index) self.set_previous_enabled.emit(self.histindex is not None and self.histindex > 0) self.set_next_enabled.emit(self.histindex is not None and \ self.histindex < len(self.history)-1)
def __init__(self, parent=None, pathlist=None, ro_pathlist=None, sync=True): QDialog.__init__(self, parent) # Destroying the C++ object right after closing the dialog box, # otherwise it may be garbage-collected in another QThread # (e.g. the editor's analysis thread in Spyder), thus leading to # a segmentation fault on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) assert isinstance(pathlist, list) self.pathlist = pathlist if ro_pathlist is None: ro_pathlist = [] self.ro_pathlist = ro_pathlist self.last_path = getcwd() self.setWindowTitle(_("PYTHONPATH manager")) self.setWindowIcon(ima.icon('pythonpath')) self.resize(500, 300) self.selection_widgets = [] layout = QVBoxLayout() self.setLayout(layout) top_layout = QHBoxLayout() layout.addLayout(top_layout) self.toolbar_widgets1 = self.setup_top_toolbar(top_layout) self.listwidget = QListWidget(self) self.listwidget.currentRowChanged.connect(self.refresh) layout.addWidget(self.listwidget) bottom_layout = QHBoxLayout() layout.addLayout(bottom_layout) self.sync_button = None self.toolbar_widgets2 = self.setup_bottom_toolbar(bottom_layout, sync) # Buttons configuration bbox = QDialogButtonBox(QDialogButtonBox.Close) bbox.rejected.connect(self.reject) bottom_layout.addWidget(bbox) self.update_list() self.refresh()
def save_dictionary(data, filename): """Save dictionary in a single file .spydata file""" filename = osp.abspath(filename) old_cwd = getcwd() os.chdir(osp.dirname(filename)) error_message = None try: saved_arrays = {} if load_array is not None: # Saving numpy arrays with np.save arr_fname = osp.splitext(filename)[0] for name in list(data.keys()): if isinstance(data[name], np.ndarray) and data[name].size > 0: # Saving arrays at data root fname = __save_array(data[name], arr_fname, len(saved_arrays)) saved_arrays[(name, None)] = osp.basename(fname) data.pop(name) elif isinstance(data[name], (list, dict)): # Saving arrays nested in lists or dictionaries if isinstance(data[name], list): iterator = enumerate(data[name]) else: iterator = iter(list(data[name].items())) to_remove = [] for index, value in iterator: if isinstance(value, np.ndarray) and value.size > 0: fname = __save_array(value, arr_fname, len(saved_arrays)) saved_arrays[(name, index)] = osp.basename(fname) to_remove.append(index) for index in sorted(to_remove, reverse=True): data[name].pop(index) if saved_arrays: data['__saved_arrays__'] = saved_arrays pickle_filename = osp.splitext(filename)[0] + '.pickle' with open(pickle_filename, 'wb') as fdesc: pickle.dump(data, fdesc, 2) tar = tarfile.open(filename, "w") for fname in [pickle_filename ] + [fn for fn in list(saved_arrays.values())]: tar.add(osp.basename(fname)) os.remove(fname) tar.close() if saved_arrays: data.pop('__saved_arrays__') except (RuntimeError, pickle.PicklingError, TypeError) as error: error_message = to_text_string(error) os.chdir(old_cwd) return error_message
def save_dictionary(data, filename): """Save dictionary in a single file .spydata file""" filename = osp.abspath(filename) old_cwd = getcwd() os.chdir(osp.dirname(filename)) error_message = None try: saved_arrays = {} if load_array is not None: # Saving numpy arrays with np.save arr_fname = osp.splitext(filename)[0] for name in list(data.keys()): if isinstance(data[name], np.ndarray) and data[name].size > 0: # Saving arrays at data root fname = __save_array(data[name], arr_fname, len(saved_arrays)) saved_arrays[(name, None)] = osp.basename(fname) data.pop(name) elif isinstance(data[name], (list, dict)): # Saving arrays nested in lists or dictionaries if isinstance(data[name], list): iterator = enumerate(data[name]) else: iterator = iter(list(data[name].items())) to_remove = [] for index, value in iterator: if isinstance(value, np.ndarray) and value.size > 0: fname = __save_array(value, arr_fname, len(saved_arrays)) saved_arrays[(name, index)] = osp.basename(fname) to_remove.append(index) for index in sorted(to_remove, reverse=True): data[name].pop(index) if saved_arrays: data['__saved_arrays__'] = saved_arrays pickle_filename = osp.splitext(filename)[0]+'.pickle' with open(pickle_filename, 'wb') as fdesc: pickle.dump(data, fdesc, 2) tar = tarfile.open(filename, "w") for fname in [pickle_filename]+[fn for fn in list(saved_arrays.values())]: tar.add(osp.basename(fname)) os.remove(fname) tar.close() if saved_arrays: data.pop('__saved_arrays__') except (RuntimeError, pickle.PicklingError, TypeError) as error: error_message = to_text_string(error) os.chdir(old_cwd) return error_message
def guess_filename(filename): """Guess filename""" if osp.isfile(filename): return filename if not filename.endswith('.py'): filename += '.py' for path in [getcwd()] + sys.path: fname = osp.join(path, filename) if osp.isfile(fname): return fname elif osp.isfile(fname + '.py'): return fname + '.py' elif osp.isfile(fname + '.pyw'): return fname + '.pyw' return filename
def guess_filename(filename): """Guess filename""" if osp.isfile(filename): return filename if not filename.endswith('.py'): filename += '.py' for path in [getcwd()] + sys.path: fname = osp.join(path, filename) if osp.isfile(fname): return fname elif osp.isfile(fname+'.py'): return fname+'.py' elif osp.isfile(fname+'.pyw'): return fname+'.pyw' return filename
def load_session(filename): """Load Spyder session""" filename = osp.abspath(filename) old_cwd = getcwd() os.chdir(osp.dirname(filename)) error_message = None renamed = False try: tar = tarfile.open(filename, "r") extracted_files = tar.getnames() # Rename original config files for fname in extracted_files: orig_name = get_conf_path(fname) bak_name = get_conf_path(fname + ".bak") if osp.isfile(bak_name): os.remove(bak_name) if osp.isfile(orig_name): os.rename(orig_name, bak_name) renamed = True tar.extractall() for fname in extracted_files: shutil.move(fname, get_conf_path(fname)) except Exception as error: error_message = to_text_string(error) if renamed: # Restore original config files for fname in extracted_files: orig_name = get_conf_path(fname) bak_name = get_conf_path(fname + ".bak") if osp.isfile(orig_name): os.remove(orig_name) if osp.isfile(bak_name): os.rename(bak_name, orig_name) finally: # Removing backup config files for fname in extracted_files: bak_name = get_conf_path(fname + ".bak") if osp.isfile(bak_name): os.remove(bak_name) os.chdir(old_cwd) return error_message
def __init__(self, parent=None, pathlist=None, ro_pathlist=None, sync=True): QDialog.__init__(self, parent) # Destroying the C++ object right after closing the dialog box, # otherwise it may be garbage-collected in another QThread # (e.g. the editor's analysis thread in Spyder), thus leading to # a segmentation fault on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) assert isinstance(pathlist, list) self.pathlist = pathlist if ro_pathlist is None: ro_pathlist = [] self.ro_pathlist = ro_pathlist self.last_path = getcwd() self.setWindowTitle(_("PYTHONPATH manager")) self.setWindowIcon(get_icon('pythonpath.png')) self.resize(500, 300) self.selection_widgets = [] layout = QVBoxLayout() self.setLayout(layout) top_layout = QHBoxLayout() layout.addLayout(top_layout) self.toolbar_widgets1 = self.setup_top_toolbar(top_layout) self.listwidget = QListWidget(self) self.connect(self.listwidget, SIGNAL("currentRowChanged(int)"), self.refresh) layout.addWidget(self.listwidget) bottom_layout = QHBoxLayout() layout.addLayout(bottom_layout) self.sync_button = None self.toolbar_widgets2 = self.setup_bottom_toolbar(bottom_layout, sync) # Buttons configuration bbox = QDialogButtonBox(QDialogButtonBox.Close) self.connect(bbox, SIGNAL("rejected()"), SLOT("reject()")) bottom_layout.addWidget(bbox) self.update_list() self.refresh()
def load_session(filename): """Load Spyder session""" filename = osp.abspath(filename) old_cwd = getcwd() os.chdir(osp.dirname(filename)) error_message = None renamed = False try: tar = tarfile.open(filename, "r") extracted_files = tar.getnames() # Rename original config files for fname in extracted_files: orig_name = get_conf_path(fname) bak_name = get_conf_path(fname + '.bak') if osp.isfile(bak_name): os.remove(bak_name) if osp.isfile(orig_name): os.rename(orig_name, bak_name) renamed = True tar.extractall() for fname in extracted_files: shutil.move(fname, get_conf_path(fname)) except Exception as error: error_message = to_text_string(error) if renamed: # Restore original config files for fname in extracted_files: orig_name = get_conf_path(fname) bak_name = get_conf_path(fname + '.bak') if osp.isfile(orig_name): os.remove(orig_name) if osp.isfile(bak_name): os.rename(bak_name, orig_name) finally: # Removing backup config files for fname in extracted_files: bak_name = get_conf_path(fname + '.bak') if osp.isfile(bak_name): os.remove(bak_name) os.chdir(old_cwd) return error_message
def save_session(filename): """Save Spyder session""" local_fname = get_conf_path(osp.basename(filename)) filename = osp.abspath(filename) old_cwd = getcwd() os.chdir(get_conf_path()) error_message = None try: tar = tarfile.open(local_fname, "w") for fname in SAVED_CONFIG_FILES: if osp.isfile(fname): tar.add(fname) tar.close() shutil.move(local_fname, filename) except Exception as error: error_message = to_text_string(error) os.chdir(old_cwd) return error_message
def include_chm_doc(plugin_dir): """Build and replace Spyder's html doc by .chm doc""" curdir = getcwd() os.chdir(osp.dirname(__file__)) os.system('sphinx-build -b htmlhelp doc doctmp') for hhc_exe in (r'C:\Program Files\HTML Help Workshop\hhc.exe', r'C:\Program Files (x86)\HTML Help Workshop\hhc.exe'): if osp.isfile(hhc_exe): break else: print >>sys.stderr, "Warning: HTML Help Workshop is not installed "\ "on this computer." return fname = osp.join('doctmp', 'Spyderdoc.chm') os.system('"%s" %s' % (hhc_exe, fname)) docdir = osp.join(plugin_dir, 'PURELIB', 'spyderlib', 'doc') shutil.rmtree(docdir) os.mkdir(docdir) shutil.copy(fname, osp.join(docdir, 'Spyderdoc.chm')) os.chdir(curdir)
def load_dictionary(filename): """Load dictionary from .spydata file""" filename = osp.abspath(filename) old_cwd = getcwd() os.chdir(osp.dirname(filename)) data = None error_message = None try: tar = tarfile.open(filename, "r") tar.extractall() pickle_filename = osp.splitext(filename)[0] + '.pickle' try: # Old format (Spyder 2.0-2.1 for Python 2) with open(pickle_filename, 'U') as fdesc: data = pickle.loads(fdesc.read()) except (pickle.PickleError, TypeError, UnicodeDecodeError): # New format (Spyder >=2.2 for Python 2 and Python 3) with open(pickle_filename, 'rb') as fdesc: data = pickle.loads(fdesc.read()) saved_arrays = {} if load_array is not None: # Loading numpy arrays saved with np.save try: saved_arrays = data.pop('__saved_arrays__') for (name, index), fname in list(saved_arrays.items()): arr = np.load(osp.join(osp.dirname(filename), fname)) if index is None: data[name] = arr elif isinstance(data[name], dict): data[name][index] = arr else: data[name].insert(index, arr) except KeyError: pass for fname in [pickle_filename ] + [fn for fn in list(saved_arrays.values())]: os.remove(fname) except (EOFError, ValueError) as error: error_message = to_text_string(error) os.chdir(old_cwd) return data, error_message
def load_dictionary(filename): """Load dictionary from .spydata file""" filename = osp.abspath(filename) old_cwd = getcwd() os.chdir(osp.dirname(filename)) data = None error_message = None try: tar = tarfile.open(filename, "r") tar.extractall() pickle_filename = osp.splitext(filename)[0] + ".pickle" try: # Old format (Spyder 2.0-2.1 for Python 2) with open(pickle_filename, "U") as fdesc: data = pickle.loads(fdesc.read()) except (pickle.PickleError, TypeError): # New format (Spyder >=2.2 for Python 2 and Python 3) with open(pickle_filename, "rb") as fdesc: data = pickle.loads(fdesc.read()) saved_arrays = {} if load_array is not None: # Loading numpy arrays saved with np.save try: saved_arrays = data.pop("__saved_arrays__") for (name, index), fname in list(saved_arrays.items()): arr = np.load(osp.join(osp.dirname(filename), fname)) if index is None: data[name] = arr elif isinstance(data[name], dict): data[name][index] = arr else: data[name].insert(index, arr) except KeyError: pass for fname in [pickle_filename] + [fn for fn in list(saved_arrays.values())]: os.remove(fname) except (EOFError, ValueError) as error: error_message = to_text_string(error) os.chdir(old_cwd) return data, error_message
def run_script(self, filename=None, silent=False, set_focus=False, args=None): """Run a Python script""" if filename is None: self.shell.interpreter.restore_stds() filename, _selfilter = getopenfilename(self, _("Run Python script"), getcwd(), _("Python scripts")+" (*.py ; *.pyw ; *.ipy)") self.shell.interpreter.redirect_stds() if filename: os.chdir( osp.dirname(filename) ) filename = osp.basename(filename) else: return filename = osp.abspath(filename) rbs = remove_backslashes command = "runfile('%s', args='%s')" % (rbs(filename), rbs(args)) if set_focus: self.shell.setFocus() if self.dockwidget and not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.raise_() self.shell.write(command+'\n') self.shell.run_command(command)
def run_c2p(self): """Prompt the user to load a combine archive, translate to Python, and display in a new window""" editorwindow = None #Used in editor.load processevents = True #Used in editor.load editor = self.main.editor basedir = getcwd() if CONF.get('workingdir', 'editor/open/browse_scriptdir'): c_fname = editor.get_current_filename() if c_fname is not None and c_fname != editor.TEMPFILE_PATH: basedir = os.path.dirname(c_fname) editor.emit(SIGNAL('redirect_stdio(bool)'), False) parent_widget = editor.get_current_editorstack() selectedfilter = '' filters = 'Combine archives (*.zip *.omex);;All files (*.*)' filenames, _selfilter = getopenfilenames(parent_widget, _("Open combine archive"), basedir, filters, selectedfilter=selectedfilter) editor.emit(SIGNAL('redirect_stdio(bool)'), True) if filenames: filenames = [os.path.normpath(fname) for fname in filenames] if CONF.get('workingdir', 'editor/open/auto_set_to_basedir'): directory = os.path.dirname(filenames[0]) editor.emit(SIGNAL("open_dir(QString)"), directory) else: #The file dialog box was closed without selecting a file. return focus_widget = QApplication.focusWidget() if editor.dockwidget and not editor.ismaximized and\ (not editor.dockwidget.isAncestorOf(focus_widget)\ and not isinstance(focus_widget, CodeEditor)): editor.dockwidget.setVisible(True) editor.dockwidget.setFocus() editor.dockwidget.raise_() def _convert(fname): fname = os.path.abspath(encoding.to_unicode_from_fs(fname)) if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':': fname = fname[0].upper() + fname[1:] return fname if hasattr(filenames, 'replaceInStrings'): # This is a QStringList instance (PyQt API #1), converting to list: filenames = list(filenames) if not isinstance(filenames, list): filenames = [_convert(filenames)] else: filenames = [_convert(fname) for fname in list(filenames)] for index, filename in enumerate(filenames): p = re.compile('(.zip$|.omex$)') pythonfile = p.sub('.py', filename) if (pythonfile == filename): pythonfile = filename + ".py" current_editor = editor.set_current_filename( pythonfile, editorwindow) if current_editor is not None: # -- TODO: Do not open an already opened file pass else: # -- Not an existing opened file: if not os.path.isfile(filename): continue # -- current_es = editor.get_current_editorstack(editorwindow) # Creating the editor widget in the first editorstack (the one # that can't be destroyed), then cloning this editor widget in # all other editorstacks: finfo, newname = self.load_and_translate( filename, pythonfile, editor) finfo.path = editor.main.get_spyder_pythonpath() editor._clone_file_everywhere(finfo) current_editor = current_es.set_current_filename(newname) #if (current_editor is not None): # editor.register_widget_shortcuts("Editor", current_editor) current_es.analyze_script() if (current_editor is not None): current_editor.clearFocus() current_editor.setFocus() current_editor.window().raise_() if processevents: QApplication.processEvents()
def __init__( self, parent=None, name_filters=["*.py", "*.pyw"], show_all=False, show_cd_only=None, show_icontext=True ): QWidget.__init__(self, parent) # Widgets self.treewidget = ExplorerTreeWidget(self, show_cd_only=show_cd_only) button_previous = QToolButton(self) button_next = QToolButton(self) button_parent = QToolButton(self) self.button_menu = QToolButton(self) menu = QMenu(self) self.action_widgets = [button_previous, button_next, button_parent, self.button_menu] # Actions icontext_action = create_action(self, _("Show icons and text"), toggled=self.toggle_icontext) previous_action = create_action( self, text=_("Previous"), icon=ima.icon("ArrowBack"), triggered=self.treewidget.go_to_previous_directory ) next_action = create_action( self, text=_("Next"), icon=ima.icon("ArrowForward"), triggered=self.treewidget.go_to_next_directory ) parent_action = create_action( self, text=_("Parent"), icon=ima.icon("ArrowUp"), triggered=self.treewidget.go_to_parent_directory ) options_action = create_action(self, text="", tip=_("Options")) # Setup widgets self.treewidget.setup(name_filters=name_filters, show_all=show_all) self.treewidget.chdir(getcwd()) self.treewidget.common_actions += [None, icontext_action] button_previous.setDefaultAction(previous_action) previous_action.setEnabled(False) button_next.setDefaultAction(next_action) next_action.setEnabled(False) button_parent.setDefaultAction(parent_action) self.button_menu.setIcon(ima.icon("tooloptions")) self.button_menu.setPopupMode(QToolButton.InstantPopup) self.button_menu.setMenu(menu) add_actions(menu, self.treewidget.common_actions) options_action.setMenu(menu) self.toggle_icontext(show_icontext) icontext_action.setChecked(show_icontext) for widget in self.action_widgets: widget.setAutoRaise(True) widget.setIconSize(QSize(16, 16)) # Layouts blayout = QHBoxLayout() blayout.addWidget(button_previous) blayout.addWidget(button_next) blayout.addWidget(button_parent) blayout.addStretch() blayout.addWidget(self.button_menu) layout = QVBoxLayout() layout.addLayout(blayout) layout.addWidget(self.treewidget) self.setLayout(layout) # Signals and slots self.treewidget.set_previous_enabled.connect(previous_action.setEnabled) self.treewidget.set_next_enabled.connect(next_action.setEnabled)
def go_to_parent_directory(self): """Go to parent directory""" self.chdir(osp.abspath(osp.join(getcwd(), os.pardir)))
def import_data(self, filenames=None): """Import data from text file""" title = _("Import data") if filenames is None: if self.filename is None: basedir = getcwd() else: basedir = osp.dirname(self.filename) filenames, _selfilter = getopenfilenames(self, title, basedir, iofunctions.load_filters) if not filenames: return elif is_text_string(filenames): filenames = [filenames] for filename in filenames: self.filename = to_text_string(filename) ext = osp.splitext(self.filename)[1].lower() if ext not in iofunctions.load_funcs: buttons = QMessageBox.Yes | QMessageBox.Cancel answer = QMessageBox.question(self, title, _("<b>Unsupported file extension '%s'</b><br><br>" "Would you like to import it anyway " "(by selecting a known file format)?" ) % ext, buttons) if answer == QMessageBox.Cancel: return formats = list(iofunctions.load_extensions.keys()) item, ok = QInputDialog.getItem(self, title, _('Open file as:'), formats, 0, False) if ok: ext = iofunctions.load_extensions[to_text_string(item)] else: return load_func = iofunctions.load_funcs[ext] # 'import_wizard' (self.setup_io) if is_text_string(load_func): # Import data with import wizard error_message = None try: text, _encoding = encoding.read(self.filename) if self.is_internal_shell: self.editor.import_from_string(text) else: base_name = osp.basename(self.filename) editor = ImportWizard(self, text, title=base_name, varname=fix_reference_name(base_name)) if editor.exec_(): var_name, clip_data = editor.get_data() monitor_set_global(self._get_sock(), var_name, clip_data) except Exception as error: error_message = str(error) else: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() if self.is_internal_shell: namespace, error_message = load_func(self.filename) interpreter = self.shellwidget.interpreter for key in list(namespace.keys()): new_key = fix_reference_name(key, blacklist=list(interpreter.namespace.keys())) if new_key != key: namespace[new_key] = namespace.pop(key) if error_message is None: interpreter.namespace.update(namespace) else: error_message = monitor_load_globals(self._get_sock(), self.filename, ext) QApplication.restoreOverrideCursor() QApplication.processEvents() if error_message is not None: QMessageBox.critical(self, title, _("<b>Unable to load '%s'</b>" "<br><br>Error message:<br>%s" ) % (self.filename, error_message)) self.refresh_table()
def _getcdlistdir(): """Return current directory list dir""" return os.listdir(getcwd())
def setup_page(self): run_dlg = _("Run Settings") run_menu = _("Run") about_label = QLabel(_("The following are the default <i>%s</i>. "\ "These options may be overriden using the "\ "<b>%s</b> dialog box (see the <b>%s</b> menu)"\ ) % (run_dlg, run_dlg, run_menu)) about_label.setWordWrap(True) interpreter_group = QGroupBox(_("Console")) interpreter_bg = QButtonGroup(interpreter_group) self.current_radio = self.create_radiobutton(CURRENT_INTERPRETER, CURRENT_INTERPRETER_OPTION, True, button_group=interpreter_bg) self.dedicated_radio = self.create_radiobutton(DEDICATED_INTERPRETER, DEDICATED_INTERPRETER_OPTION, False, button_group=interpreter_bg) self.systerm_radio = self.create_radiobutton(SYSTERM_INTERPRETER, SYSTERM_INTERPRETER_OPTION, False, button_group=interpreter_bg) interpreter_layout = QVBoxLayout() interpreter_group.setLayout(interpreter_layout) interpreter_layout.addWidget(self.current_radio) interpreter_layout.addWidget(self.dedicated_radio) interpreter_layout.addWidget(self.systerm_radio) wdir_group = QGroupBox(_("Working directory")) wdir_bg = QButtonGroup(wdir_group) wdir_label = QLabel(_("Default working directory is:")) wdir_label.setWordWrap(True) dirname_radio = self.create_radiobutton(_("the script directory"), WDIR_USE_SCRIPT_DIR_OPTION, True, button_group=wdir_bg) thisdir_radio = self.create_radiobutton(_("the following directory:"), WDIR_USE_FIXED_DIR_OPTION, False, button_group=wdir_bg) thisdir_bd = self.create_browsedir("", WDIR_FIXED_DIR_OPTION, getcwd()) thisdir_radio.toggled.connect(thisdir_bd.setEnabled) dirname_radio.toggled.connect(thisdir_bd.setDisabled) thisdir_layout = QHBoxLayout() thisdir_layout.addWidget(thisdir_radio) thisdir_layout.addWidget(thisdir_bd) wdir_layout = QVBoxLayout() wdir_layout.addWidget(wdir_label) wdir_layout.addWidget(dirname_radio) wdir_layout.addLayout(thisdir_layout) wdir_group.setLayout(wdir_layout) firstrun_cb = self.create_checkbox( ALWAYS_OPEN_FIRST_RUN % _("Run Settings dialog"), ALWAYS_OPEN_FIRST_RUN_OPTION, False) vlayout = QVBoxLayout() vlayout.addWidget(about_label) vlayout.addSpacing(10) vlayout.addWidget(interpreter_group) vlayout.addWidget(wdir_group) vlayout.addWidget(firstrun_cb) vlayout.addStretch(1) self.setLayout(vlayout)
def getcwd(self): """Return current working directory""" return getcwd()