示例#1
0
def _writeToFile(expression_string, model_directory, parent, header):
    """
    Writes a compound model expression to file.

    Parameters
    ----------
    expression_string: str
        The model expression to write.

    model_directory: str
        The path to write the model to.

    parent: QtWidget
        The parent widget the file dialog should belong to.

    header: str
        The 'header' string contains the import statements that refer to
        each component type that appear in the expression.
    """

    fname = compat.getsavefilename(parent=parent,
                                   caption='Export to .py file',
                                   basedir=model_directory)[0]

    if len(fname) > 0:
        # enforce correct suffix.
        if not fname.endswith(".py"):
            fname += ".py"

        f = open(fname, 'w')

        f.write(header)
        f.write(expression_string)
        f.close()
示例#2
0
    def _setup_save_path(self):
        """
        Prompt the user for a file to save comments and flags into.
        """
        fail = True
        success = False
        info = "Where would you like to save comments and flags?"
        option = pick_item([0, 1],
            [os.path.basename(self.filepath), "New MOSViz Table file"],
            label=info,  title="Comment Setup")
        if option == 0:
            self.savepath = self.filepath
        elif option == 1:
            dirname = os.path.dirname(self.filepath)
            path = compat.getsavefilename(caption="New MOSViz Table File",
                basedir=dirname, filters="*.txt")[0]
            if path == "":
                return fail
            self.savepath = path
        else:
            return fail

        for v in self.session.application.viewers[0]:
            if isinstance(v, MOSVizViewer):
                if v.data_idx == self.data_idx:
                    v.savepath = self.savepath
        self._layer_view.refresh()
        return success
示例#3
0
    def _on_export_plot(self):
        file_path, key = compat.getsavefilename(filters=";;".join(
            EXPORT_FILTERS.keys()))

        if key == '':
            return

        exporter = EXPORT_FILTERS[key](self.plot_widget.plotItem)

        # TODO: Current issue in pyqtgraph where the user cannot explicitly
        # define the output size. Fix incoming.

        # plot_size_dialog = PlotSizeDialog(self)
        # plot_size_dialog.height_line_edit.setText(
        #     str(int(exporter.params.param('height').value())))
        # plot_size_dialog.width_line_edit.setText(
        #     str(int(exporter.params.param('width').value())))
        #
        # if key != "*.svg":
        #     if plot_size_dialog.exec_():
        #         exporter.params.param('height').setValue(int(exporter.params.param('height').value()),
        #                                                  blockSignal=exporter.heightChanged)
        #         exporter.params.param('width').setValue(int(exporter.params.param('height').value()),
        #                                                  blockSignal=exporter.widthChanged)
        #     else:
        #         return

        exporter.export(file_path)
示例#4
0
 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)
示例#5
0
    def save_yaml(self, event=None):

        if self.ui.loader_name.text() == "":
            self.ui.label_loader_name_status.setText(
                'Enter a name for the loader')
            self.ui.label_loader_name_status.setStyleSheet('color: red')
            return

        specviz_dir = os.path.join(os.path.expanduser('~'), '.specviz')
        if not os.path.exists(specviz_dir):
            os.mkdir(specviz_dir)

        filename = compat.getsavefilename(
            parent=self,
            caption='Export loader to .yaml file',
            basedir=specviz_dir)[0]

        if filename == '':
            return

        filename = "{}.yaml".format(
            filename) if not filename.endswith(".yaml") else filename

        string = self.as_yaml()
        with open(filename, 'w') as f:
            f.write(string)
示例#6
0
    def _setup_save_path(self):
        """
        Prompt the user for a file to save comments and flags into.
        """
        fail = True
        success = False
        info = "Where would you like to save comments and flags?"
        option = pick_item(
            [0, 1], [os.path.basename(self.filepath), "New MOSViz Table file"],
            label=info,
            title="Comment Setup")
        if option == 0:
            self.savepath = self.filepath
        elif option == 1:
            dirname = os.path.dirname(self.filepath)
            path = compat.getsavefilename(caption="New MOSViz Table File",
                                          basedir=dirname,
                                          filters="*.txt")[0]
            if path == "":
                return fail
            self.savepath = path
        else:
            return fail

        for v in self.session.application.viewers[0]:
            if isinstance(v, MOSVizViewer):
                if v.data_idx == self.data_idx:
                    v.savepath = self.savepath
        self._layer_view.refresh()
        return success
示例#7
0
文件: dialog.py 项目: sunn-e/glue
def export_data(data, components=None, exporter=None):

    if exporter is None:
        exporters = {}
        for e in config.data_exporter:
            if e.extension == '':
                fltr = "{0} (*)".format(e.label)
            else:
                fltr = "{0} ({1})".format(e.label, ' '.join('*.' + ext for ext in e.extension))
            exporters[fltr] = e.function
        filters = ';;'.join(sorted(exporters))
    else:
        filters = None

    filename, fltr = compat.getsavefilename(caption="Choose an output filename",
                                            filters=filters)

    filename = str(filename)
    if not filename:
        return

    if filters is not None:
        exporter = exporters[fltr]

    exporter(filename, data, components=components)
示例#8
0
    def _on_export_data(self):
        """
        Handler function that is called when the Export Data button is pressed
        """
        all_filters = ";;".join(['*.ecsv'])
        path, fmt = compat.getsavefilename(filters=all_filters)

        if path and fmt:
            try:
                plot_data_item = self.current_item
                self.export_data_item(plot_data_item, path, fmt)

                message_box = QMessageBox()
                message_box.setText("Data exported successfully.")
                message_box.setIcon(QMessageBox.Information)
                message_box.setInformativeText(
                    "Data set '{}' has been exported to '{}'".format(
                        plot_data_item.data_item.name, path))

                message_box.exec()
            except Exception as e:
                logging.error(e)

                message_box = QMessageBox()
                message_box.setText("Error exporting data set.")
                message_box.setIcon(QMessageBox.Critical)
                message_box.setInformativeText(
                    "{}\n{}".format(
                        sys.exc_info()[0], sys.exc_info()[1].__repr__()[:100])
                )

                message_box.exec()
示例#9
0
 def slotOnExportFilenames(self):
     filename = getsavefilename(self, _("Record all time-series filenames"),
                                'files.dat', _('list (*.list)'), None,
                                QFileDialog.DontUseNativeDialog)[0]
     if filename:
         with open(filename, 'w') as f:
             f.write("\n".join(self.files))
示例#10
0
 def save_as(self, name=None, close=False):
     """Save notebook as."""
     current_client = self.get_current_client()
     current_client.save()
     original_path = current_client.get_filename()
     if not name:
         original_name = osp.basename(original_path)
     else:
         original_name = name
     filename, _selfilter = getsavefilename(self, _("Save notebook"),
                                            original_name, FILES_FILTER)
     if filename:
         try:
             nb_contents = nbformat.read(original_path, as_version=4)
         except EnvironmentError as error:
             txt = (_("Error while reading {}<p>{}").format(
                 original_path, str(error)))
             QMessageBox.critical(self, _("File Error"), txt)
             return
         try:
             nbformat.write(nb_contents, filename)
         except EnvironmentError as error:
             txt = (_("Error while writing {}<p>{}").format(
                 filename, str(error)))
             QMessageBox.critical(self, _("File Error"), txt)
             return
         if not close:
             self.close_client(save=True)
         self.create_new_client(filename=filename)
示例#11
0
    def save_loader_script(self, event=None, output_directory=None):
        """
        oputput_directory parameter is strictly for use in tests.
        """

        if not self.save_loader_check():
            return

        specutils_dir = os.path.join(os.path.expanduser('~'), '.specutils')

        if not os.path.exists(specutils_dir):
            os.mkdir(specutils_dir)

        loader_name = self.ui.loader_name.text()

        # If the loader name already exists in the registry, raise a warning
        # and ask the user to pick another name
        if loader_name in registry.get_formats(Spectrum1D, 'Read')['Format']:
            QMessageBox.information(
                self,
                "Loader name already exists.",
                "A loader with the name '{}' already exists in the registry. "
                "Please choose a different name.".format(loader_name))

            return

        out_path = os.path.join(specutils_dir, loader_name)

        filename = compat.getsavefilename(parent=self,
                                          caption='Export loader to .py file',
                                          basedir=out_path)[0]
        if filename == '':
            return

        self.save_register_new_loader(filename)
示例#12
0
    def save_figure_as(self, fig, fmt):
        """Save the figure to a file."""
        fext, ffilt = {
            'image/png': ('.png', 'PNG (*.png)'),
            'image/jpeg': ('.jpg', 'JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)'),
            'image/svg+xml': ('.svg', 'SVG (*.svg);;PNG (*.png)')
        }[fmt]

        figname = get_unique_figname(
            self.save_dir,
            'Figure ' + datetime.datetime.now().strftime('%Y-%m-%d %H%M%S'),
            fext)

        self.sig_redirect_stdio_requested.emit(False)
        fname, fext = getsavefilename(parent=self.parent(),
                                      caption='Save Figure',
                                      basedir=figname,
                                      filters=ffilt,
                                      selectedfilter='',
                                      options=None)
        self.sig_redirect_stdio_requested.emit(True)

        if fname:
            self.sig_save_dir_changed.emit(osp.dirname(fname))
            save_figure_tofile(fig, fmt, fname)
示例#13
0
    def _choose_save(self):

        out, _ = compat.getsavefilename(filters='FITS Files (*.fits)')
        if out is None:
            return

        self.save_to(out)
示例#14
0
    def _choose_save_session(self, *args):
        """ Save the data collection and hub to file.

        Can be restored via restore_session
        """

        # include file filter twice, so it shows up in Dialog
        outfile, file_filter = compat.getsavefilename(
            parent=self,
            basedir=getattr(self, '_last_session_name', 'session.glu'),
            filters=("Glue Session with absolute paths to data (*.glu);; "
                     "Glue Session with relative paths to data (*.glu);; "
                     "Glue Session including data (*.glu)"),
            selectedfilter=getattr(
                self, '_last_session_filter',
                'Glue Session with relative paths to data (*.glu)'))

        # This indicates that the user cancelled
        if not outfile:
            return

        # Add extension if not specified
        if '.' not in outfile:
            outfile += '.glu'

        self._last_session_name = outfile
        self._last_session_filter = file_filter

        with set_cursor_cm(Qt.WaitCursor):
            self.save_session(outfile,
                              include_data="including data" in file_filter,
                              absolute_paths="absolute" in file_filter)
        self._on_session_changed(outfile)
示例#15
0
def _writeToFile(out_model_dict, model_directory, parent):
    """
    Writes a dict to YAML file.

    Parameters
    ----------
    out_model_dict: dict
        The model dictionary to write.

    model_directory: str
        The path to write to

    parent: QtWidget
        The parent widget to make the file dialog belong to.
        May be None.
    """

    fname = compat.getsavefilename(parent=parent,
                                   caption='Save to file',
                                   basedir=model_directory)[0]

    if len(fname) > 0:
        # enforce correct suffix.
        if not fname.endswith(".yaml"):
            fname += ".yaml"

        f = open(fname, "w")
        yaml.dump(out_model_dict, f, default_flow_style=False)
        f.close()
示例#16
0
    def create_new_file(self, current_path, title, filters, create_func):
        """
        Create new file.

        Returns True if successful.
        """
        if current_path is None:
            current_path = ''
        if osp.isfile(current_path):
            current_path = osp.dirname(current_path)
        self.redirect_stdio.emit(False)
        fname, _selfilter = getsavefilename(self, title, current_path, filters)
        self.redirect_stdio.emit(True)
        if fname:
            try:
                create_func(fname)
                return fname
            except EnvironmentError as error:
                msg_box = MessageBoxError(
                    text="<b>Unable to create file <i>%s</i>"
                    "</b><br><br>Error message:<br>%s" %
                    (fname, to_text_string(error)),
                    title='New file error',
                )
                msg_box.exec_()
示例#17
0
    def _on_export_plot(self):
        file_path, key = compat.getsavefilename(
            filters=";;".join(EXPORT_FILTERS.keys()))

        if key == '':
            return

        exporter = EXPORT_FILTERS[key](self.plot_widget.plotItem)

        # TODO: Current issue in pyqtgraph where the user cannot explicitly
        # define the output size. Fix incoming.

        # plot_size_dialog = PlotSizeDialog(self)
        # plot_size_dialog.height_line_edit.setText(
        #     str(int(exporter.params.param('height').value())))
        # plot_size_dialog.width_line_edit.setText(
        #     str(int(exporter.params.param('width').value())))
        #
        # if key != "*.svg":
        #     if plot_size_dialog.exec_():
        #         exporter.params.param('height').setValue(int(exporter.params.param('height').value()),
        #                                                  blockSignal=exporter.heightChanged)
        #         exporter.params.param('width').setValue(int(exporter.params.param('height').value()),
        #                                                  blockSignal=exporter.widthChanged)
        #     else:
        #         return

        exporter.export(file_path)
示例#18
0
    def save_loader_script(self, event=None, output_directory=None):
        """
        oputput_directory parameter is strictly for use in tests.
        """

        if not self.save_loader_check():
            return

        specutils_dir = os.path.join(os.path.expanduser('~'), '.specutils')

        if not os.path.exists(specutils_dir):
            os.mkdir(specutils_dir)

        loader_name = self.ui.loader_name.text()

        # If the loader name already exists in the registry, raise a warning
        # and ask the user to pick another name
        if loader_name in registry.get_formats(Spectrum1D, 'Read')['Format']:
            QMessageBox.information(
                self, "Loader name already exists.",
                "A loader with the name '{}' already exists in the registry. "
                "Please choose a different name.".format(loader_name))

            return

        out_path = os.path.join(specutils_dir, loader_name)

        filename = compat.getsavefilename(parent=self,
                                          caption='Export loader to .py file',
                                          basedir=out_path)[0]
        if filename == '':
            return

        self.save_register_new_loader(filename)
示例#19
0
    def save_data(self, filename=None):
        """Save data"""
        if filename is None:
            filename = self.filename
            if filename is None:
                filename = getcwd_or_home()
            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()

        error_message = self.shellwidget.save_namespace(self.filename)
        self.shellwidget._kernel_reply = None

        QApplication.restoreOverrideCursor()
        QApplication.processEvents()
        if error_message is not None:
            if 'Some objects could not be saved:' in error_message:
                save_data_message = (
                    _('<b>Some objects could not be saved:</b>')
                    + '<br><br><code>{obj_list}</code>'.format(
                        obj_list=error_message.split(': ')[1]))
            else:
                save_data_message = _(
                    '<b>Unable to save current workspace</b>'
                    '<br><br>Error message:<br>') + error_message
            QMessageBox.critical(self, _("Save data"), save_data_message)
        self.save_button.setEnabled(self.filename is not None)
示例#20
0
    def save_data(self, filename=None):
        """Save data"""
        if filename is None:
            filename = self.filename
            if filename is None:
                filename = getcwd_or_home()
            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()

        error_message = self.shellwidget.save_namespace(self.filename)
        self.shellwidget._kernel_reply = None

        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)
示例#21
0
    def _on_export_data(self):
        """
        Handler function that is called when the Export Data button is pressed
        """
        all_filters = ";;".join(['*.ecsv'])
        path, fmt = compat.getsavefilename(filters=all_filters)

        if path and fmt:
            try:
                plot_data_item = self.current_item
                self.export_data_item(plot_data_item, path, fmt)

                message_box = QMessageBox()
                message_box.setText("Data exported successfully.")
                message_box.setIcon(QMessageBox.Information)
                message_box.setInformativeText(
                    "Data set '{}' has been exported to '{}'".format(
                        plot_data_item.data_item.name, path))

                message_box.exec()
            except Exception as e:
                logging.error(e)

                message_box = QMessageBox()
                message_box.setText("Error exporting data set.")
                message_box.setIcon(QMessageBox.Critical)
                message_box.setInformativeText("{}\n{}".format(
                    sys.exc_info()[0],
                    sys.exc_info()[1].__repr__()[:100]))

                message_box.exec()
示例#22
0
    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()

        error_message = self.shellwidget.save_namespace(self.filename)
        self.shellwidget._kernel_reply = None

        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)
示例#23
0
    def _choose_save(self):

        out, _ = compat.getsavefilename(filters='FITS Files (*.fits)')
        if out is None:
            return

        self.save_to(out)
示例#24
0
    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)
示例#25
0
    def save_data(self, filename=None):
        """Save data"""
        if filename is None:
            filename = self.filename
            if filename is None:
                filename = getcwd_or_home()
            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()

        error_message = self.shellwidget.save_namespace(self.filename)

        QApplication.restoreOverrideCursor()
        QApplication.processEvents()
        if error_message is not None:
            if 'Some objects could not be saved:' in error_message:
                save_data_message = (
                    _("<b>Some objects could not be saved:</b>")
                    + "<br><br><code>{obj_list}</code>".format(
                        obj_list=error_message.split(': ')[1]))
            else:
                save_data_message = _(
                    "<b>Unable to save current workspace</b>"
                    "<br><br>"
                    "The error message was:<br>") + error_message
            QMessageBox.critical(self, _("Save data"), save_data_message)
        self.save_button.setEnabled(self.filename is not None)
示例#26
0
 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)
示例#27
0
    def _choose_save_session(self, *args):
        """ Save the data collection and hub to file.

        Can be restored via restore_session
        """

        # include file filter twice, so it shows up in Dialog
        outfile, file_filter = compat.getsavefilename(
            parent=self, basedir=getattr(self, '_last_session_name', 'session.glu'),
            filters=("Glue Session with absolute paths to data (*.glu);; "
                     "Glue Session with relative paths to data (*.glu);; "
                     "Glue Session including data (*.glu)"),
            selectedfilter=getattr(self, '_last_session_filter',
                                   'Glue Session with relative paths to data (*.glu)'))

        # This indicates that the user cancelled
        if not outfile:
            return

        # Add extension if not specified
        if '.' not in outfile:
            outfile += '.glu'

        self._last_session_name = outfile
        self._last_session_filter = file_filter

        with set_cursor_cm(Qt.WaitCursor):
            self.save_session(outfile,
                              include_data="including data" in file_filter,
                              absolute_paths="absolute" in file_filter)
示例#28
0
 def save_data(self):
     """Save data"""
     title = _("Save profiler result")
     filename, _selfilter = getsavefilename(
         self, title, getcwd_or_home(),
         _("Profiler result") + " (*.Result)")
     if filename:
         self.datatree.save_data(filename)
示例#29
0
 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)
示例#30
0
 def slotOnExportDiscontinuities(self):
     filename = getsavefilename(self,
                                "Save discontinuities into file",
                                "",
                                self.tr("*.json"),
                                None,
                                QFileDialog.DontUseNativeDialog)[0]
     if filename:
         self.sig_discontinuity_file_exported.emit(filename)
示例#31
0
    def exportToFile(self):
        file_name, fltr = compat.getsavefilename(
            caption="Choose an output filename")

        try:
            self.data_frame.to_csv(str(file_name), index=False)
        except:
            print("passed")
            pass
示例#32
0
    def _choose_save(self):

        self._aggregate()

        out, _ = compat.getsavefilename(filters='FITS Files (*.fits)')
        if not out:
            return

        self.save_to(out)
示例#33
0
def save_subset(subset):
    assert isinstance(subset, core.subset.Subset)
    fname, fltr = compat.getsavefilename(
        caption="Select an output name",
        filters='FITS mask (*.fits);; Fits mask (*.fits)')
    fname = str(fname)
    if not fname:
        return
    subset.write_mask(fname)
示例#34
0
    def _choose_save(self):

        self._aggregate()

        out, _ = compat.getsavefilename(filters='FITS Files (*.fits)')
        if not out:
            return

        self.save_to(out)
示例#35
0
 def slotOnSaveData(self):
     text = self.analysisDock.tsAnalysisWidget.dataCombo.currentText()
     data = self.dataAnalysisResult.get(text, None)
     if data is not None:
         filename = getsavefilename(self.analysisDock,
                                    "Save data into file", "", "*.dat",
                                    None,
                                    QFileDialog.DontUseNativeDialog)[0]
         if filename:
             self.reader.saveTODAT(data, filename)
示例#36
0
    def activate(self):

        filename, _ = compat.getsavefilename(parent=self.viewer, basedir="make_plot.py")

        if not filename:
            return

        if not filename.endswith('.py'):
            filename += '.py'

        self.viewer.export_as_script(filename)
    def save_as(self, name=None, reopen_after_save=True):
        """
        Save current notebook under a different file name.

        First, save the notebook under the original file name. Then ask user
        for a new file name (if `name` is not set), and return if no new name
        is given. Then, read the contents of the notebook that was just saved
        and write them under the new file name. If `reopen_after_save` is
        True, then close the original tab and open a new tab with the
        notebook loaded from the new file name.

        Parameters
        ----------
        name : str or None, optional
            File name under which the notebook is to be saved. The default is
            None, meaning that the user should be asked for the file name.
        reopen_after_save : bool, optional
            Whether to close the original tab and re-open it under the new
            file name after saving the notebook. The default is True.

        Returns
        -------
        The file name of the notebook.
        """
        current_client = self.currentWidget()
        current_client.save()
        original_path = current_client.get_filename()
        if not name:
            original_name = osp.basename(original_path)
        else:
            original_name = name
        filename, _selfilter = getsavefilename(self, _("Save notebook"),
                                               original_name, FILES_FILTER)
        if not filename:
            return original_path

        try:
            nb_contents = nbformat.read(original_path, as_version=4)
        except EnvironmentError as error:
            txt = (_("Error while reading {}<p>{}")
                   .format(original_path, str(error)))
            QMessageBox.critical(self, _("File Error"), txt)
            return original_path
        try:
            nbformat.write(nb_contents, filename)
        except EnvironmentError as error:
            txt = (_("Error while writing {}<p>{}")
                   .format(filename, str(error)))
            QMessageBox.critical(self, _("File Error"), txt)
            return original_path
        if reopen_after_save:
            self.close_client(save_before_close=False)
            self.create_new_client(filename=filename)
        return filename
示例#38
0
    def activate(self):

        filename, _ = compat.getsavefilename(parent=self.viewer, basedir="make_plot.py")

        if not filename:
            return

        if not filename.endswith('.py'):
            filename += '.py'

        self.viewer.export_as_script(filename)
示例#39
0
    def export_snippets(self):
        filename, _selfilter = getsavefilename(
            self,
            _("Save snippets"),
            'spyder_snippets.json',
            filters='JSON (*.json)',
            selectedfilter='',
            options=QFileDialog.HideNameFilterDetails)

        if filename:
            filename = osp.normpath(filename)
            self.snippets_proxy.export_snippets(filename)
示例#40
0
    def activate(self):

        # pop up a window for file saving
        outfile, file_filter = compat.getsavefilename(
            caption='Save Animation', filters='GIF Files (*.gif);;')

        # if outfile is not set, the user cancelled
        if outfile:
            import imageio
            self.set_icon(RECORD_STOP_ICON)
            self.writer = imageio.get_writer(outfile)
            self.record_timer.start(0.1)
示例#41
0
    def activate(self):

        filename, _ = compat.getsavefilename(caption='Save File',
                                             filters='PNG Files (*.png);;'
                                                      'JPEG Files (*.jpeg);;'
                                                      'TIFF Files (*.tiff);;',
                                             selectedfilter='PNG Files (*.png);;')

        # This indicates that the user cancelled
        if not filename:
            return

        self.viewer._wwt_client.render(filename)
示例#42
0
文件: tools.py 项目: jsub1/glue-wwt
    def activate(self):

        filename, _ = compat.getsavefilename(
            caption='Save File',
            filters='PNG Files (*.png);;'
            'JPEG Files (*.jpeg);;'
            'TIFF Files (*.tiff);;',
            selectedfilter='PNG Files (*.png);;')

        # This indicates that the user cancelled
        if not filename:
            return

        self.viewer._wwt.render(filename)
示例#43
0
文件: tools.py 项目: jsub1/glue-wwt
    def activate(self):

        app = get_qapp()

        filename, _ = compat.getsavefilename(
            caption='Save File',
            basedir='mytour.wtt',
            filters='WWT Tour File (*.wtt);;',
            selectedfilter='WWT Tour File (*.wtt);;')

        # This indicates that the user cancelled
        if not filename:
            return

        if not filename.endswith('.wtt'):
            filename = filename + '.wtt'

        self.viewer._wwt.widget.page.runJavaScript("tourxml = '';",
                                                   asynchronous=False)
        tourxml = self.viewer._wwt.widget.page.runJavaScript(
            'tourxml;', asynchronous=False)

        self.viewer._wwt.widget.page.runJavaScript(SAVE_TOUR_CODE)

        start = time.time()
        tourxml = None
        while time.time() - start < 10:
            time.sleep(0.1)
            app.processEvents()
            tourxml = self.viewer._wwt.widget.page.runJavaScript(
                'tourxml;', asynchronous=False)
            if tourxml:
                break

        if not tourxml:
            raise Exception("Failed to save tour")

        # Patch the altUnit so that it is correct for the Windows client (since
        # the web client currently has other bugs with relation to loading tours).
        # https://github.com/WorldWideTelescope/wwt-web-client/issues/248
        for unit_int in range(1, 11):
            altunit_str = 'AltUnit="{0}"'.format(unit_int)
            if altunit_str in tourxml:
                altunit_str_new = 'AltUnit="{0}"'.format(unit_int - 1)
                print('Changing {0} to {1} in {2}'.format(
                    altunit_str, altunit_str_new, filename))
                tourxml = tourxml.replace(altunit_str, altunit_str_new)

        with io.open(filename, 'w', newline='') as f:
            f.write(tourxml)
示例#44
0
文件: application.py 项目: pllim/glue
 def _choose_export_session(self, saver, checker, outmode):
     checker(self)
     if outmode is None:
         return saver(self)
     elif outmode in ['file', 'directory']:
         outfile, file_filter = compat.getsavefilename(parent=self)
         if not outfile:
             return
         return saver(self, outfile)
     else:
         assert outmode == 'label'
         label, ok = QtWidgets.QInputDialog.getText(self, 'Choose a label:',
                                                    'Choose a label:')
         if not ok:
             return
         return saver(self, label)
示例#45
0
文件: shell.py 项目: cfanpc/spyder
 def save_historylog(self):
     """Save current history log (all text in console)"""
     title = _("Save history log")
     self.redirect_stdio.emit(False)
     filename, _selfilter = getsavefilename(self, title,
                 self.historylog_filename, "%s (*.log)" % _("History logs"))
     self.redirect_stdio.emit(True)
     if filename:
         filename = osp.normpath(filename)
         try:
             encoding.write(to_text_string(self.get_text_with_eol()),
                            filename)
             self.historylog_filename = filename
             CONF.set('main', 'historylog_filename', filename)
         except EnvironmentError:
             pass
示例#46
0
    def save_figure(self):
        outfile, file_filter = getsavefilename(caption='Save File',
                                               filters='PNG Files (*.png);;'
                                                       'JPEG Files (*.jpeg);;'
                                                       'TIFF Files (*.tiff);;')

        # This indicates that the user cancelled
        if not outfile:
            return
        img = self._vispy_widget.canvas.render()
        try:
            file_filter = str(file_filter).split()[0]
            io.imsave(outfile, img, format=file_filter)
        except ImportError:
            # TODO: give out a window to notify that only .png file format is supported
            if not '.' in outfile:
                outfile += '.png'
            io.write_png(outfile, img)
示例#47
0
 def toggle_record(self):
     if self.record_action.isChecked():
         # pop up a window for file saving
         outfile, file_filter = getsavefilename(caption='Save Animation',
                                                filters='GIF Files (*.gif);;')
         # This indicates that the user cancelled
         if not outfile:
             self.record_action.blockSignals(True)
             self.record_action.setChecked(False)
             self.record_action.blockSignals(False)
             return
         self.record_action.setIcon(QtGui.QIcon(RECORD_STOP_ICON))
         self.writer = imageio.get_writer(outfile)
         self.record_timer.start(0.1)
     else:
         self.record_timer.stop()
         self.record_action.setIcon(QtGui.QIcon(RECORD_START_ICON))
         self.writer.close()
示例#48
0
    def _export_to_file(self, file_name=None):
        if file_name is None:

            if hasattr(self, '_plotted_lines_pane') and self._plotted_lines_pane:

                filters = ['Line list (*.ecsv)']
                file_name, _file_filter = compat.getsavefilename(filters=";;".join(filters))

                if not file_name.endswith('.ecsv'):
                    file_name += '.ecsv'

                output_table = self._plotted_lines_pane.plotted_lines.table

                for colum_name in columns_to_remove:
                    if colum_name in output_table.colnames:
                        output_table.remove_column(colum_name)

                ascii.write(output_table, output=file_name, format='ecsv')
示例#49
0
    def save_figure_as(self, fig, fmt):
        """Save the figure to a file."""
        fext, ffilt = {
            'image/png': ('.png', 'PNG (*.png)'),
            'image/jpeg': ('.jpg', 'JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)'),
            'image/svg+xml': ('.svg', 'SVG (*.svg);;PNG (*.png)')}[fmt]

        figname = get_unique_figname(getcwd_or_home(), 'Figure', fext)

        self.redirect_stdio.emit(False)
        fname, fext = getsavefilename(
            parent=self.parent(), caption='Save Figure',
            basedir=figname, filters=ffilt,
            selectedfilter='', options=None)
        self.redirect_stdio.emit(True)

        if fname:
            save_figure_tofile(fig, fmt, fname)
示例#50
0
 def create_new_file(self, current_path, title, filters, create_func):
     """Create new file
     Returns True if successful"""
     if current_path is None:
         current_path = ''
     if osp.isfile(current_path):
         current_path = osp.dirname(current_path)
     self.parent_widget.redirect_stdio.emit(False)
     fname, _selfilter = getsavefilename(self, title, current_path, filters)
     self.parent_widget.redirect_stdio.emit(True)
     if fname:
         try:
             create_func(fname)
             return fname
         except EnvironmentError as error:
             QMessageBox.critical(self, _("New file"),
                                  _("<b>Unable to create file <i>%s</i>"
                                    "</b><br><br>Error message:<br>%s"
                                    ) % (fname, to_text_string(error)))
示例#51
0
 def save_historylog(self):
     """Save current history log (all text in console)"""
     title = _("Save history log")
     self.redirect_stdio.emit(False)
     filename, _selfilter = getsavefilename(self, title,
                 self.historylog_filename, "%s (*.log)" % _("History logs"))
     self.redirect_stdio.emit(True)
     if filename:
         filename = osp.normpath(filename)
         try:
             encoding.write(to_text_string(self.get_text_with_eol()),
                            filename)
             self.historylog_filename = filename
             CONF.set('main', 'historylog_filename', filename)
         except EnvironmentError as error:
             QMessageBox.critical(self, title,
                                  _("<b>Unable to save file '%s'</b>"
                                    "<br><br>Error message:<br>%s"
                                    ) % (osp.basename(filename),
                                         to_text_string(error)))
示例#52
0
文件: application.py 项目: pllim/glue
    def _choose_save_session(self):
        """ Save the data collection and hub to file.

        Can be restored via restore_session
        """

        # include file filter twice, so it shows up in Dialog
        outfile, file_filter = compat.getsavefilename(
            parent=self, filters=("Glue Session (*.glu);; "
                                  "Glue Session including data (*.glu)"))

        # This indicates that the user cancelled
        if not outfile:
            return

        # Add extension if not specified
        if '.' not in outfile:
            outfile += '.glu'

        with set_cursor_cm(Qt.WaitCursor):
            self.save_session(
                outfile, include_data="including data" in file_filter)
示例#53
0
    def activate(self):

        if self.next_action == 'start':

            # pop up a window for file saving
            outfile, file_filter = compat.getsavefilename(caption='Save Animation',
                                                          filters='GIF Files (*.gif);;')

            # if outfile is not set, the user cancelled
            if outfile:
                import imageio
                self.set_icon(RECORD_STOP_ICON)
                self.writer = imageio.get_writer(outfile)
                self.record_timer.start(0.1)
                self.next_action = 'stop'

        else:

            self.record_timer.stop()
            if self.writer is not None:
                self.writer.close()
            self.set_icon(RECORD_START_ICON)
            self.next_action = 'start'
示例#54
0
def save_as(filename, title='Save As...'):
    """Creates a Save File dialog and returns a filename."""
    result = compat.getsavefilename(parent=active_window(),
                                    caption=title,
                                    basedir=filename)
    return result[0]