def create_load_file_dialog(self, qt_wildcard, title, default_filename=None): #options = QFileDialog.Options() #options |= QFileDialog.DontUseNativeDialog #if qt_version == 4: ## works in: pyqt4, pyside ## doesn't work in: pyqt5 #fname, wildcard_level = QFileDialog.getOpenFileNameAndFilter( #self, title, default_filename, file_types, options=options) #return str(fname), str(wildcard_level) #else: #fname, flt = QFileDialog.getOpenFileName( #self, title, default_filename, file_types, options=options) ##flt = str(filt).strip() #return fname, flt if default_filename is None: default_filename = self.gui.last_dir fname, wildcard_level = getopenfilename(parent=self.gui, caption=title, basedir=default_filename, filters=qt_wildcard, selectedfilter='', options=None) return wildcard_level, fname
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_or_home(), _("Python scripts") + " (*.py ; *.pyw ; *.ipy)") self.shell.interpreter.redirect_stds() if filename: os.chdir(osp.dirname(filename)) filename = osp.basename(filename) else: return logger.debug("Running script with %s", args) 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: self.switch_to_plugin() self.shell.write(command + '\n') self.shell.run_command(command)
def select_file(self, filename=None): """ Select filename to profile. Parameters ---------- filename: str, optional Path to filename to profile. default is None. Notes ----- If no `filename` is provided an open filename dialog will be used. """ if filename is None: self.sig_redirect_stdio_requested.emit(False) filename, _selfilter = getopenfilename( self, _("Select Python script"), getcwd_or_home(), _("Python scripts") + " (*.py ; *.pyw)" ) self.sig_redirect_stdio_requested.emit(True) if filename: self.analyze(filename)
def _on_load_data(self): """ When the user loads a data file, this method is triggered. It provides a file open dialog and from the dialog attempts to create a new :class:`~specutils.Spectrum1D` object and thereafter adds it to the data model. """ # This ensures that users actively have to select a file type before # being able to select a file. This should make it harder to # accidentally load a file using the wrong type, which results in weird # errors. default_filter = '-- Select file type --' filters = [default_filter] + [x['Format'] + " (*)" for x in io_registry.get_formats(Spectrum1D) if x['Read'] == 'Yes'] file_path, fmt = compat.getopenfilename(parent=self, caption="Load spectral data file", filters=";;".join(filters), selectedfilter=default_filter) if not file_path: return self.load_data(file_path, file_loader=" ".join(fmt.split()[:-1]))
def add_license(self, v=None, path=None): """Add license file.""" if path is None: filename, selected_filter = getopenfilename( self, 'Select license file', filters='License files (*.txt)', basedir=get_home_dir(), ) if filename: paths = [filename] else: paths = [] else: paths = [path] valid_licenses, invalid_licenses = self.api.add_license(paths) for path in invalid_licenses: text = ('File: <b>"{0}"</b>' '<br>is not a valid license file.').format(path) self.message_box = MessageBoxInformation( text=text, title="Invalid license file") self.message_box.exec_() if valid_licenses: self.load_licenses()
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 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_or_home(), _("Python scripts")+" (*.py ; *.pyw ; *.ipy)") self.shell.interpreter.redirect_stds() if filename: os.chdir( osp.dirname(filename) ) filename = osp.basename(filename) else: return logger.debug("Running script with %s", args) 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_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_or_home(), _("Python scripts") + " (*.py ; *.pyw ; *.ipy)") self.shell.interpreter.redirect_stds() if filename: os.chdir(osp.dirname(filename)) filename = osp.basename(filename) else: return debug_print(args) 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 select_file(self, edit, filters=None, new=False): """Select file. :param edit: box to display the selected file. :type edit: QLineEdit :param filters: filters by filename extension :type filters: str :param new: select existing or create new file. :type new: bool """ initdir = to_text_string(edit.text()) if osp.isdir(initdir): basedir = initdir else: basedir = osp.dirname(initdir) if not osp.isdir(basedir): basedir = getcwd_or_home() if filters is None: filters = _("All files (*)") title = _("Select file") if new: filename, _selfilter = getsavefilename(self, title, basedir, filters) else: filename, _selfilter = getopenfilename(self, title, basedir, filters) if filename: edit.setText(filename) self.load_lines() # Push default object name if self.object_name is not None: path, fn = osp.split(filename) object_name = osp.splitext(fn)[0] self.object_name.edit.setText(object_name)
def select_file(self): self.redirect_stdio.emit(False) filename, _selfilter = getopenfilename(self, _("Select Python file"), getcwd(), _("Python files")+" (*.py ; *.pyw)") self.redirect_stdio.emit(True) if filename: self.analyze(filename)
def choose(self): """Display file dialog to select environment specification.""" selected_filter = None if self.radio_spec.isChecked(): path, selected_filter = getopenfilename( caption="Import Project", basedir=HOME_PATH, parent=None, filters="{0};;{1};;{2}".format( self.CONDA_ENV_FILES, self.CONDA_SPEC_FILES, self.PIP_REQUIREMENT_FILES ) ) else: path = getexistingdirectory( caption="Import Project", basedir=HOME_PATH, parent=None, ) if path: name = self.text_name.text() self.selected_file_filter = selected_filter self.text_path.setText(path) self.refresh(path) self.text_name.setText(name)
def choose(self): """Display file dialog to select environment specification.""" path, selected_filter = getopenfilename( caption="Import Environment", basedir=os.path.expanduser('~'), parent=None, filters="{0};;{1};;{2}".format(self.CONDA_ENV_FILES, self.CONDA_SPEC_FILES, self.PIP_REQUIREMENT_FILES)) if path: name = self.name self.selected_file_filter = selected_filter self.text_path.setText(path) self.refresh(path) # Try to get the name key of the file if an environment.yaml file if selected_filter == self.CONDA_ENV_FILES: try: with open(path, 'r') as f: raw = f.read() data = yaml.load(raw) name = data.get('name', name) except Exception: pass self.text_name.setText(name)
def get_img_path(self): browse_input = compat.getopenfilename(filters=" ".join(self.imageExt))[0] self.raise_() if browse_input == "": return self.img_path = browse_input self.image_user_input.setText(self.img_path) self.image_user_input.setStyleSheet("")
def compare(self): filename, _selfilter = getopenfilename( self, _("Select script to compare"), getcwd_or_home(), _("Profiler result") + " (*.Result)") if filename: self.datatree.compare(filename) self.show_data() self.clear_button.setEnabled(True)
def select_model(self): """Select Model file/dir""" basedir = to_text_string(self.wd_edit.text()) if not os.path.isdir(basedir): basedir = getcwd_or_home() file, no_use = getopenfilename(self, _("Select Model"), basedir) if file: self.wd_edit.setText(file)
def create_load_file_dialog(self, qt_wildcard, title, default_filename=None): if default_filename is None: default_filename = self.gui.last_dir fname, wildcard_level = getopenfilename( parent=self.gui, caption=title, basedir=default_filename, filters=qt_wildcard, selectedfilter='', options=None) return wildcard_level, fname
def select_file(self): self.redirect_stdio.emit(False) filename, _selfilter = getopenfilename( self, _("Select Python script"), getcwd_or_home(), _("Python scripts") + " (*.py ; *.pyw)") self.redirect_stdio.emit(True) if filename: self.analyze(filename)
def on_offsetButton_clicked(self): # filename = self.dialog.getOpenFileName( # self, 'Choose Offsets file', '', self.tr('*.json'), # None, QFileDialog.DontUseNativeDialog) # filename = u"%s" % filename filename = getopenfilename(self, 'Choose Offsets file', '', self.tr('*.json'), None, QFileDialog.DontUseNativeDialog)[0] self.offsetEdit.setText(filename)
def run_script(self): """Run a Python script""" self.redirect_stdio.emit(False) filename, _selfilter = getopenfilename(self, _("Run Python script"), getcwd(), _("Python scripts")+" (*.py ; *.pyw ; *.ipy)") self.redirect_stdio.emit(True) if filename: self.start(fname=filename, wdir=None, args='', interact=False, debug=False)
def _choose_file_path(self): filters, loader_name_map = self._create_loader_filters() file_path, fmt = compat.getopenfilename(parent=self, basedir=os.getcwd(), caption="Load spectral data file", filters=";;".join(filters)) return file_path, loader_name_map[fmt]
def open_image(self): """Open image file""" saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr sys.stdout = None filename, _filter = getopenfilename(self, _("Open"), "", io.iohandler.get_filters("load")) sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err if filename: self.mainwidget.add_image_from_file(filename)
def get_target_path(self): browse_input = compat.getopenfilename(filters="*.txt")[0] self.raise_() if browse_input == "": return self.target_file_path = browse_input self.target_user_input.setText(self.target_file_path) self.target_user_input.setStyleSheet("") self.update_save()
def slotOnImportDiscontinuities(self): filename = getopenfilename(self, 'Choose Offsets file', '', self.tr('*.json'), None, QFileDialog.DontUseNativeDialog)[0] if filename: self.sig_discontinuity_file_imported.emit(filename)
def _choose_file_path(self): filters, loader_name_map = self._create_loader_filters() file_path, fmt = compat.getopenfilename( parent=self, basedir=os.getcwd(), caption="Load spectral data file", filters=";;".join(filters)) return file_path, loader_name_map[fmt]
def _restore_session(self, show=True): """ Load a previously-saved state, and restart the session """ fltr = "Glue sessions (*.glu)" file_name, file_filter = compat.getopenfilename( parent=self, filters=fltr) if not file_name: return ga = self.restore_session_and_close(file_name) return ga
def _restore_session(self, *args): """ Load a previously-saved state, and restart the session """ fltr = "Glue sessions (*.glu)" file_name, file_filter = compat.getopenfilename(parent=self, filters=fltr) if not file_name: return ga = self.restore_session_and_close(file_name) return ga
def select_file(self, edit, filters=None): """Select File""" basedir = osp.dirname(to_text_string(edit.text())) if not osp.isdir(basedir): basedir = getcwd_or_home() if filters is None: filters = _("All files (*)") title = _("Select file") filename, _selfilter = getopenfilename(self, title, basedir, filters) if filename: edit.setText(filename)
def _restore_session(self, show=True): """ Load a previously-saved state, and restart the session """ fltr = "Glue sessions (*.glu)" file_name, file_filter = compat.getopenfilename(parent=self, filters=fltr) if not file_name: return with set_cursor_cm(Qt.WaitCursor): ga = self.restore_session(file_name) self.close() return ga
def _restore_session(self, show=True): """ Load a previously-saved state, and restart the session """ fltr = "Glue sessions (*.glu)" file_name, file_filter = compat.getopenfilename( parent=self, filters=fltr) if not file_name: return with set_cursor_cm(Qt.WaitCursor): ga = self.restore_session(file_name) self.close() return ga
def _click_addOffsetButton(self): # dialog = QFileDialog(self) filename = getopenfilename(self, 'Choose Offsets file', '', self.tr('*.json'), None, QFileDialog.DontUseNativeDialog)[0] filename = u"%s" % filename if filename: self.offsetEdit.setText(filename) if self.site: offset = get_offsets(self.site.lower(), file=filename) self._add_offsets(offset) self.offsets_file = filename
def import_snippets(self): filename, _sf = getopenfilename( self, _("Load snippets"), filters='JSON (*.json)', selectedfilter='', options=QFileDialog.HideNameFilterDetails, ) if filename: filename = osp.normpath(filename) valid, total, errors = self.snippets_proxy.import_snippets( filename) modified = True if len(errors) == 0: QMessageBox.information( self, _('All snippets imported'), _('{0} snippets were loaded successfully').format(valid), QMessageBox.Ok) else: if 'loading' in errors: modified = False QMessageBox.critical( self, _('JSON malformed'), _('There was an error when trying to load the ' 'provided JSON file: <tt>{0}</tt>').format( errors['loading']), QMessageBox.Ok) elif 'validation' in errors: modified = False QMessageBox.critical( self, _('Invalid snippet file'), _('The provided snippet file does not comply with ' 'the Spyder JSON snippets spec and therefore it ' 'cannot be loaded.<br><br><tt>{}</tt>').format( errors['validation']), QMessageBox.Ok) elif 'syntax' in errors: syntax_errors = errors['syntax'] msg = [] for syntax_key in syntax_errors: syntax_err = syntax_errors[syntax_key] msg.append('<b>{0}</b>: {1}'.format( syntax_key, syntax_err)) err_msg = '<br>'.join(msg) QMessageBox.warning( self, _('Incorrect snippet format'), _('Spyder was able to load {0}/{1} snippets ' 'correctly, please check the following snippets ' 'for any syntax errors: ' '<br><br>{2}').format(valid, total, err_msg), QMessageBox.Ok) self.set_modified(modified)
def compare(self): """Compare previous saved run with last run.""" filename, _selfilter = getopenfilename( self, _("Select script to compare"), getcwd_or_home(), _("Profiler result") + " (*.Result)", ) if filename: self.datatree.compare(filename) self.show_data() self.clear_action.setEnabled(True)
def select_icon(self): """ """ out = getopenfilename( caption='Select icon', filters='PNG Image (*.png)', ) logger.debug(str(out)) if out[0]: with open(out[0], 'rb') as f: image = f.read() self.project.icon = base64.b64encode(image) self.project.save(self.path) self.load_icon()
def get_filename_and_reader(self): subset_mask_importers = _make_filters_dict(config.subset_mask_importer) filters = ';;'.join(sorted(subset_mask_importers)) filename, fltr = compat.getopenfilename(caption="Choose a subset mask file", filters=filters) filename = str(filename) if filename: return filename, subset_mask_importers[fltr] else: return None, None
def open_wizard(): filters = ["FITS, ECSV, text (*.fits *.ecsv *.dat *.txt)"] filename, file_filter = compat.getopenfilename(filters=";;".join(filters)) if filename == '': return if filename.lower().endswith('fits'): dialog = FITSImportWizard(simplify_arrays(parse_fits(filename))) elif filename.lower().endswith('ecsv'): dialog = ECSVImportWizard(simplify_arrays(parse_ecsv(filename))) elif filename.lower().endswith('dat') or filename.lower().endswith('txt'): dialog = ASCIIImportWizard(simplify_arrays(parse_ascii(filename))) else: raise NotImplementedError(file_filter) val = dialog.exec_() if val == 0: return # Make temporary YAML file yaml_file = tempfile.mktemp() with open(yaml_file, 'w') as f: f.write(dialog.as_yaml(name=str(uuid.uuid4()))) # Temporarily load YAML file yaml_filter = load_yaml_reader(yaml_file) def remove_yaml_filter(data): # Just some checking in the edge case where a user is simultaneously loading another file... if data.name != os.path.basename(filename).split('.')[0]: return io_registry._readers.pop((yaml_filter, Spectrum1DRef)) io_registry._identifiers.pop((yaml_filter, Spectrum1DRef)) dispatch.unregister_listener("on_added_data", remove_yaml_filter) dispatch.register_listener("on_added_data", remove_yaml_filter) # Emit signal to indicate that file should be read dispatch.on_file_read.emit(file_name=filename, file_filter=yaml_filter)
def create_load_file_dialog(self, qt_wildcard: str, title: str, default_filename: Optional[str]=None) -> Tuple[str, str]: #options = QFileDialog.Options() #options |= QFileDialog.DontUseNativeDialog #fname, flt = QFileDialog.getOpenFileName( #self, title, default_filename, file_types, options=options) #flt = str(filt).strip() #return fname, flt if default_filename is None: default_filename = self.gui.last_dir fname, wildcard_level = getopenfilename( parent=self.gui, caption=title, basedir=default_filename, filters=qt_wildcard, selectedfilter='', options=None) return wildcard_level, fname
def open_wizard(self): """ Opens loader wizard plugin interface. """ filters = ["FITS, ECSV, text (*.fits *.ecsv *.dat *.txt *.*)"] filename, file_filter = compat.getopenfilename(filters=";;".join(filters)) if filename == '': return dialog = ASCIIImportWizard(filename, simplify_arrays(parse_ascii(filename, read_input=None))) val = dialog.exec_() if val == 0: return # Make temporary YAML file yaml_file = tempfile.mktemp() with open(yaml_file, 'w') as f: f.write(dialog.as_new_loader(name=str(uuid.uuid4())))
def select_connection_file(self): cf = getopenfilename(self, _('Select kernel connection file'), jupyter_runtime_dir(), '*.json;;*.*')[0] self.cf.setText(cf)
def open_file(title, directory=None): """Creates an Open File dialog and returns a filename.""" result = compat.getopenfilename(parent=active_window(), caption=title, basedir=directory) return result[0]
def select_ssh_key(self): kf = getopenfilename(self, _('Select SSH keyfile'), get_home_dir(), '*.pem;;*')[0] self.kf.setText(kf)