Example #1
0
def test_widget():
    """Run conda packages widget test"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = CondaPackagesWidget(None)
    widget.show()
    sys.exit(app.exec_())
Example #2
0
def oedit(obj):
    """
    Edit the object 'obj' in a GUI-based editor and return the edited copy
    (if Cancel is pressed, return None)

    The object 'obj' is a container
    
    Supported container types:
    dict, list, tuple, str/unicode or numpy.array
    
    (instantiate a new QApplication if necessary,
    so it can be called directly from the interpreter)
    """
    # Local import
    from spyderlib.widgets.texteditor import TextEditor
    from spyderlib.widgets.dicteditor import DictEditor, ndarray, FakeObject
    from spyderlib.widgets.arrayeditor import ArrayEditor
    from spyderlib.utils.qthelpers import qapplication
    _app = qapplication()

    if isinstance(obj, ndarray) and ndarray is not FakeObject:
        dialog = ArrayEditor()
        if dialog.setup_and_check(obj):
            if dialog.exec_():
                return obj
    elif isinstance(obj, (str, unicode)):
        dialog = TextEditor(obj)
        if dialog.exec_():
            return dialog.get_copy()
    elif isinstance(obj, (dict, tuple, list)):
        dialog = DictEditor(obj)
        if dialog.exec_():
            return dialog.get_copy()
    else:
        raise RuntimeError("Unsupported datatype")
Example #3
0
def test(text):
    """Test"""
    from spyderlib.utils.qthelpers import qapplication
    _app = qapplication()  # analysis:ignore
    dialog = ImportWizard(None, text)
    if dialog.exec_():
        print(dialog.get_data())
Example #4
0
def test():
    """Run Find in Files widget test"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = FindInFilesWidget(None)
    widget.show()
    sys.exit(app.exec_())
Example #5
0
def test():
    from spyderlib.utils.qthelpers import qapplication

    app = qapplication()

    from spyderlib.plugins.variableexplorer import VariableExplorer

    settings = VariableExplorer.get_settings()

    shell = ExternalPythonShell(
        pythonexecutable=sys.executable,
        interact=True,
        stand_alone=settings,
        wdir=osp.dirname(__file__),
        mpl_backend=0,
        light_background=False,
    )

    from spyderlib.qt.QtGui import QFont
    from spyderlib.config.main import CONF

    font = QFont(CONF.get("console", "font/family")[0])
    font.setPointSize(10)
    shell.shell.set_font(font)

    shell.shell.toggle_wrap_mode(True)
    shell.start_shell(False)
    shell.show()
    sys.exit(app.exec_())
Example #6
0
def test():
    """Run path manager test"""
    from spyderlib.utils.qthelpers import qapplication
    _app = qapplication()  # analysis:ignore
    test = PathManager(None, sys.path[:-10], sys.path[-10:])
    test.exec_()
    print(test.get_path_list())
Example #7
0
def test():
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    table = ShortcutsTable()
    table.show()
    app.exec_()
    print [str(s) for s in table.model.shortcuts]
def test():
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    from spyderlib.widgets.externalshell.pythonshell import ExternalPythonShell
    from spyderlib.widgets.externalshell.systemshell import ExternalSystemShell
    import spyderlib
    from spyderlib.plugins.variableexplorer import VariableExplorer
    settings = VariableExplorer.get_settings()
    shell = ExternalPythonShell(wdir=osp.dirname(spyderlib.__file__),
                                ipykernel=True, stand_alone=settings,
                                arguments="-q4thread -pylab -colors LightBG",
                                light_background=False)
#    shell = ExternalPythonShell(wdir=osp.dirname(spyderlib.__file__),
#                                interact=True, umr_enabled=True,
#                                stand_alone=settings,
#                                umr_namelist=['guidata', 'guiqwt'],
#                                umr_verbose=True, light_background=False)
#    shell = ExternalSystemShell(wdir=osp.dirname(spyderlib.__file__),
#                                light_background=False)
    shell.shell.toggle_wrap_mode(True)
    shell.start_shell(False)
    from spyderlib.qt.QtGui import QFont
    font = QFont("Lucida console")
    font.setPointSize(10)
    shell.shell.set_font(font)
    shell.show()
    sys.exit(app.exec_())
Example #9
0
def test():
    """Run breakpoint widget test"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = BreakpointWidget(None)
    widget.show()
    sys.exit(app.exec_())
Example #10
0
def test():
    """Array editor test"""
    _app = qapplication()
    
    arr = np.array(["kjrekrjkejr"])
    print("out:", test_edit(arr, "string array"))
    from spyderlib.py3compat import u
    arr = np.array([u("kjrekrjkejr")])
    print("out:", test_edit(arr, "unicode array"))
    arr = np.ma.array([[1, 0], [1, 0]], mask=[[True, False], [False, False]])
    print("out:", test_edit(arr, "masked array"))
    arr = np.zeros((2, 2), {'names': ('red', 'green', 'blue'),
                           'formats': (np.float32, np.float32, np.float32)})
    print("out:", test_edit(arr, "record array"))
    arr = np.array([(0, 0.0), (0, 0.0), (0, 0.0)],
                   dtype=[(('title 1', 'x'), '|i1'),
                          (('title 2', 'y'), '>f4')])
    print("out:", test_edit(arr, "record array with titles"))
    arr = np.random.rand(5, 5)
    print("out:", test_edit(arr, "float array",
                            xlabels=['a', 'b', 'c', 'd', 'e']))
    arr = np.round(np.random.rand(5, 5)*10)+\
                   np.round(np.random.rand(5, 5)*10)*1j
    print("out:", test_edit(arr, "complex array",
                            xlabels=np.linspace(-12, 12, 5),
                            ylabels=np.linspace(-12, 12, 5)))
    arr_in = np.array([True, False, True])
    print("in:", arr_in)
    arr_out = test_edit(arr_in, "bool array")
    print("out:", arr_out)
    print(arr_in is arr_out)
    arr = np.array([1, 2, 3], dtype="int8")
    print("out:", test_edit(arr, "int array"))
Example #11
0
def main():
    """Run Windows environment variable editor"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    dialog = WinUserEnvDialog()
    dialog.show()
    app.exec_()
Example #12
0
def test():
    """Run file/directory explorer test"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    test = Test()
    test.show()
    sys.exit(app.exec_())
Example #13
0
def test_dialog():
    """Run conda packages widget test"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    dialog = CondaPackagesDialog(name='root')
    dialog.exec_()
    sys.exit(app.exec_())
Example #14
0
def main():
    """Run web browser"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = PydocBrowser(None)
    widget.show()
    widget.initialize()
    sys.exit(app.exec_())
Example #15
0
def test():  # pragma: no cover
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    dlg_table = NumpyArrayDialog(None, inline=False)
    dlg_inline = NumpyArrayDialog(None, inline=True)
    dlg_table.show()
    dlg_inline.show()
    app.exec_()
Example #16
0
def test():
    """Run pylint widget test"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = PylintWidget(None)
    widget.show()
    widget.analyze(__file__)
    sys.exit(app.exec_())
def test():
    """Run RateLaw widget test"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = RateLawWidget(None)
    widget.resize(400, 300)
    widget.show()
    sys.exit(app.exec_())
Example #18
0
def construct_editor(text):
    app = qapplication()
    editor = CodeEditor(parent=None)
    editor.setup_editor(language='Python')
    editor.set_text(text)
    cursor = editor.textCursor()
    cursor.movePosition(QTextCursor.End)
    editor.setTextCursor(cursor)
    return editor
Example #19
0
def main():
    """Run web browser"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = WebBrowser()
    widget.show()
    widget.set_home_url('http://localhost:7464/')
    widget.go_home()
    sys.exit(app.exec_())
Example #20
0
def test(fname):
    """Show class browser for Python script *fname*"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = ClassBrowser(None)
    data = (fname, None, None)
    widget.refresh(data)
    widget.show()
    sys.exit(app.exec_())
Example #21
0
def test():
    """Run widget test"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = ProfilerWidget(None)
    widget.show()
    #widget.analyze(__file__)
    widget.analyze('/var/tmp/test001.py')
    sys.exit(app.exec_())
Example #22
0
def test():
    """Run web browser"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication(test_time=8)
    widget = WebBrowser()
    widget.show()
    widget.set_home_url('http://www.google.com/')
    widget.go_home()
    sys.exit(app.exec_())
Example #23
0
def test(file_explorer):
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    if file_explorer:
        test = FileExplorerTest()
    else:
        test = ProjectExplorerTest()
    test.resize(640, 480)
    test.show()
    app.exec_()
Example #24
0
def test():
    """Run widget test"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = ProfilerWidget(None)
    widget.resize(800, 600)
    widget.show()
    #widget.analyze(__file__)
    widget.analyze(osp.join(osp.dirname(__file__), os.pardir, os.pardir,
                            'rope_profiling', 'test.py'))
    sys.exit(app.exec_())
def test():
    """Run widget test"""
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = MemoryProfilerWidget(None)
    widget.resize(800, 600)
    widget.show()
    widget.analyze(osp.normpath(osp.join(osp.dirname(__file__), os.pardir,
                                         'tests/profiling_test_script.py')),
                   use_colors=True)
    sys.exit(app.exec_())
Example #26
0
def get_indent_fix(text):
    app = qapplication()
    editor = CodeEditor(parent=None)
    editor.setup_editor(language='Python')

    editor.set_text(text)
    cursor = editor.textCursor()
    cursor.movePosition(QTextCursor.End)
    editor.setTextCursor(cursor)
    editor.fix_indent()
    return to_text_string(editor.toPlainText())
Example #27
0
def test_widget():
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = DialogChannels(
        None,
        ['http://repo.continuum.io/free', 'https://conda.anaconda.org/malev'],
        ['https://conda.anaconda.org/malev'],
        'https://conda.anaconda.org',
        )
    widget.show()
    sys.exit(app.exec_())
Example #28
0
def test_edit(data, title="", parent=None):
    """Test subroutine"""
    app = qapplication()                  # analysis:ignore
    dlg = DataFrameEditor(parent=parent)

    if dlg.setup_and_check(data, title=title):
        dlg.exec_()
        return dlg.get_value()
    else:
        import sys
        sys.exit(1)
Example #29
0
def test_msgcheckbox():
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    box = MessageCheckBox()
    box.setWindowTitle(_("Spyder updates"))
    box.setText("Testing checkbox")
    box.set_checkbox_text("Check for updates on startup?")
    box.setStandardButtons(QMessageBox.Ok)
    box.setDefaultButton(QMessageBox.Ok)
    box.setIcon(QMessageBox.Information)
    box.exec_()
Example #30
0
def remote_editor_test():
    """Remote dictionary editor test"""
    from spyderlib.widgets.externalshell.namespacebrowser import get_settings
    from spyderlib.widgets.externalshell.monitor import make_remote_view
    remote = make_remote_view(get_test_data(), get_settings())
    from pprint import pprint
    pprint(remote)
    _app = qapplication()
    dialog = DictEditor(remote, remote=True)
    if dialog.exec_():
        print dialog.get_copy()
Example #31
0
def test():
    """ """
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    app.setStyle('Plastique')

    dlg_inline = NumpyArrayDialog(None, inline=True)
    dlg_table = NumpyArrayDialog(None, inline=False)

    if dlg_inline.exec_():
        print(dlg_inline.text())

    if dlg_table.exec_():
        print(dlg_table.text())
Example #32
0
def test():
    from spyderlib.qt.QtGui import QMainWindow
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication(test_time=5)
    win = QMainWindow()
    win.setWindowTitle("Status widgets test")
    win.resize(900, 300)
    statusbar = win.statusBar()
    swidgets = []
    for klass in (ReadWriteStatus, EOLStatus, EncodingStatus,
                  CursorPositionStatus, MemoryStatus, CPUStatus):
        swidget = klass(win, statusbar)
        swidgets.append(swidget)
    win.show()
    app.exec_()
Example #33
0
    def __init__(self, parent=None):

        self.configCls = PyfabConfigStandalone
        PyfabConfigSpyder.plugin = self
        self.config = self
        PyfabConfigSpyder.__init__(self)

        pyfab_app.Autolayout.__init__(self)
        self.AppCls = qapplication().__class__
        SpyderPluginMixin.__init__(self, parent)

        # Initialize plugin
        self.initialize_plugin()

        self.raise_()  #useless
Example #34
0
def test():
    """Run dependency widget test"""
    from spyderlib import dependencies

    # Test sample
    dependencies.add("IPython", "Enhanced Python interpreter", ">=0.13")
    dependencies.add("matplotlib", "Interactive data plotting", ">=1.0")
    dependencies.add("sympy", "Symbolic Mathematics", ">=10.0")
    dependencies.add("foo", "Non-existent module", ">=1.0")

    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    dlg = DependenciesDialog(None)
    dlg.set_data(dependencies.DEPENDENCIES)
    dlg.show()
    sys.exit(dlg.exec_())
Example #35
0
def test():
    """Text editor demo"""
    from spyderlib.utils.qthelpers import qapplication
    _app = qapplication()  # analysis:ignore
    dialog = TextEditor("""
    01234567890123456789012345678901234567890123456789012345678901234567890123456789
    dedekdh elkd ezd ekjd lekdj elkdfjelfjk e
    """)
    dialog.show()
    if dialog.exec_():
        text = dialog.get_value()
        print("Accepted:", text)
        dialog = TextEditor(text)
        dialog.exec_()
    else:
        print("Canceled")
Example #36
0
def test():
    import os.path as osp
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    shell = ExternalSystemShell(wdir=osp.dirname(__file__),
                                light_background=False)

    from spyderlib.qt.QtGui import QFont
    from spyderlib.config.main import CONF
    font = QFont(CONF.get('console', 'font/family')[0])
    font.setPointSize(10)
    shell.shell.set_font(font)

    shell.shell.toggle_wrap_mode(True)
    shell.start_shell(False)
    shell.show()
    sys.exit(app.exec_())
Example #37
0
def test():
    """Array editor test"""
    _app = qapplication()

    arr = np.array(["kjrekrjkejr"])
    print("out:", test_edit(arr, "string array"))
    from spyderlib.py3compat import u
    arr = np.array([u("kjrekrjkejr")])
    print("out:", test_edit(arr, "unicode array"))
    arr = np.ma.array([[1, 0], [1, 0]], mask=[[True, False], [False, False]])
    print("out:", test_edit(arr, "masked array"))
    arr = np.zeros(
        (2, 2), {
            'names': ('red', 'green', 'blue'),
            'formats': (np.float32, np.float32, np.float32)
        })
    print("out:", test_edit(arr, "record array"))
    arr = np.array([(0, 0.0), (0, 0.0), (0, 0.0)],
                   dtype=[(('title 1', 'x'), '|i1'),
                          (('title 2', 'y'), '>f4')])
    print("out:", test_edit(arr, "record array with titles"))
    arr = np.random.rand(5, 5)
    print("out:",
          test_edit(arr, "float array", xlabels=['a', 'b', 'c', 'd', 'e']))
    arr = np.round(np.random.rand(5, 5)*10)+\
                   np.round(np.random.rand(5, 5)*10)*1j
    print(
        "out:",
        test_edit(arr,
                  "complex array",
                  xlabels=np.linspace(-12, 12, 5),
                  ylabels=np.linspace(-12, 12, 5)))
    arr_in = np.array([True, False, True])
    print("in:", arr_in)
    arr_out = test_edit(arr_in, "bool array")
    print("out:", arr_out)
    print(arr_in is arr_out)
    arr = np.array([1, 2, 3], dtype="int8")
    print("out:", test_edit(arr, "int array"))
    arr = np.zeros((3, 3, 4))
    arr[0, 0, 0] = 1
    arr[0, 0, 1] = 2
    arr[0, 0, 2] = 3
    print("out:", test_edit(arr))
Example #38
0
def test():
    """Run widget test"""
    import inspect
    import tempfile
    from spyderlib.utils.qthelpers import qapplication

    primes_sc = inspect.getsource(primes)
    fd, script = tempfile.mkstemp(suffix='.py')
    with os.fdopen(fd, 'w') as f:
        f.write("# -*- coding: utf-8 -*-" + "\n\n")
        f.write(primes_sc + "\n\n")
        f.write("primes(100000)")

    app = qapplication(test_time=5)
    widget = ProfilerWidget(None)
    widget.resize(800, 600)
    widget.show()
    widget.analyze(script)
    sys.exit(app.exec_())
Example #39
0
def oedit(obj, modal=True, namespace=None):
    """Edit the object 'obj' in a GUI-based editor and return the edited copy
    (if Cancel is pressed, return None)

    The object 'obj' is a container
    
    Supported container types:
    dict, list, tuple, str/unicode or numpy.array
    
    (instantiate a new QApplication if necessary,
    so it can be called directly from the interpreter)
    """
    # Local import
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    
    if modal:
        obj_name = ''
    else:
        assert is_text_string(obj)
        obj_name = obj
        if namespace is None:
            namespace = globals()
        keeper.set_namespace(namespace)
        obj = namespace[obj_name]
        # keep QApplication reference alive in the Python interpreter:
        namespace['__qapp__'] = app
    
    result = create_dialog(obj, obj_name)
    if result is None:
        return
    dialog, end_func = result
    
    if modal:
        if dialog.exec_():
            return end_func(dialog)
    else:
        keeper.create_dialog(dialog, obj_name, end_func)
        import os
        qt_inputhook = os.environ.get("INSTALL_QT_INPUTHOOK",
                                      "").lower() == "true"
        if os.name == 'nt' and not qt_inputhook:
            app.exec_()
Example #40
0
def test_edit(data,
              title="",
              xlabels=None,
              ylabels=None,
              readonly=False,
              parent=None):
    """Test subroutine"""
    app = qapplication(test_time=1.5)  # analysis:ignore
    dlg = ArrayEditor(parent)

    if dlg.setup_and_check(data,
                           title,
                           xlabels=xlabels,
                           ylabels=ylabels,
                           readonly=readonly):
        dlg.exec_()
        return dlg.get_value()
    else:
        import sys
        sys.exit(1)
Example #41
0
def fedit(data, title="", comment="", icon=None, parent=None, apply=None):
    """
    Create form dialog and return result
    (if Cancel button is pressed, return None)
    
    data: datalist, datagroup
    title: string
    comment: string
    icon: QIcon instance
    parent: parent QWidget
    apply: apply callback (function)
    
    datalist: list/tuple of (field_name, field_value)
    datagroup: list/tuple of (datalist *or* datagroup, title, comment)
    
    -> one field for each member of a datalist
    -> one tab for each member of a top-level datagroup
    -> one page (of a multipage widget, each page can be selected with a combo
       box) for each member of a datagroup inside a datagroup
       
    Supported types for field_value:
      - int, float, str, unicode, bool
      - colors: in Qt-compatible text form, i.e. in hex format or name (red,...)
                (automatically detected from a string)
      - list/tuple:
          * the first element will be the selected index (or value)
          * the other elements can be couples (key, value) or only values
    """
    # Create a QApplication instance if no instance currently exists
    # (e.g. if the module is used directly from the interpreter)
    test_travis = os.environ.get('TEST_TRAVIS_WIDGETS', None)
    if test_travis is not None:
        from spyderlib.utils.qthelpers import qapplication
        _app = qapplication(test_time=1)
    elif QApplication.startingUp():
        _app = QApplication([])

    dialog = FormDialog(data, title, comment, icon, parent, apply)
    if dialog.exec_():
        return dialog.get()
Example #42
0
def test():
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()

    from spyderlib.plugins.variableexplorer import VariableExplorer
    settings = VariableExplorer.get_settings()

    shell = ExternalPythonShell(pythonexecutable=sys.executable,
                                interact=True,
                                stand_alone=settings,
                                wdir=osp.dirname(__file__),
                                mpl_backend=0,
                                light_background=False)

    from spyderlib.config.gui import get_font

    font = get_font()
    shell.shell.set_font(font)

    shell.shell.toggle_wrap_mode(True)
    shell.start_shell(False)
    shell.show()
    sys.exit(app.exec_())
Example #43
0
def test():
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()

    from spyderlib.plugins.variableexplorer import VariableExplorer
    settings = VariableExplorer.get_settings()

    shell = ExternalPythonShell(pythonexecutable=sys.executable,
                                interact=True,
                                stand_alone=settings,
                                wdir=osp.dirname(__file__),
                                mpl_backend=0,
                                light_background=False)

    from spyderlib.qt.QtGui import QFont
    from spyderlib.config.main import CONF
    font = QFont(CONF.get('console', 'font/family')[0])
    font.setPointSize(10)
    shell.shell.set_font(font)

    shell.shell.toggle_wrap_mode(True)
    shell.start_shell(False)
    shell.show()
    sys.exit(app.exec_())
Example #44
0
def test():
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    widget = FindInFiles()
    widget.show()
    sys.exit(app.exec_())
Example #45
0
        sys.exit()


def test():
    """DataFrame editor test"""
    from numpy import nan

    df1 = DataFrame(
        [[True, "bool"], [1 + 1j, "complex"], ['test', "string"],
         [1.11, "float"], [1, "int"], [np.random.rand(3, 3), "Unkown type"],
         ["Large value", 100], ["áéí", "unicode"]],
        index=['a', 'b', nan, nan, nan, 'c', "Test global max", 'd'],
        columns=[nan, 'Type'])
    out = test_edit(df1)
    print("out:", out)
    out = test_edit(df1.iloc[0])
    print("out:", out)
    df1 = DataFrame(np.random.rand(100001, 10))
    # Sorting large DataFrame takes time
    df1.sort(columns=[0, 1], inplace=True)
    out = test_edit(df1)
    print("out:", out)
    out = test_edit(TimeSeries(np.arange(10)))
    print("out:", out)
    return out


if __name__ == '__main__':
    _app = qapplication()
    df = test()
Example #46
0
def main():
    # Splash screen
    # -------------------------------------------------------------------------
    # Start Qt Splash to inform the user of the current status
    app = qapplication()
    restarter = Restarter()
    resample = not IS_WINDOWS
    # Resampling SVG icon only on non-Windows platforms (see Issue 1314):
    icon = ima.icon('spyder', resample=resample)
    app.setWindowIcon(icon)
    restarter.set_splash_message(_('Closing Spyder'))

    # Get variables
    # Note: Variables defined in spyderlib\spyder.py 'restart()' method
    spyder_args = os.environ.pop('SPYDER_ARGS', None)
    pid = os.environ.pop('SPYDER_PID', None)
    is_bootstrap = os.environ.pop('SPYDER_IS_BOOTSTRAP', None)
    reset = os.environ.pop('SPYDER_RESET', None)

    # Get the spyder base folder based on this file
    spyder_folder = osp.split(osp.dirname(osp.abspath(__file__)))[0]

    if not any([spyder_args, pid, is_bootstrap, reset]):
        error = "This script can only be called from within a Spyder instance"
        raise RuntimeError(error)

    # Variables were stored as string literals in the environment, so to use
    # them we need to parse them in a safe manner.
    is_bootstrap = ast.literal_eval(is_bootstrap)
    pid = ast.literal_eval(pid)
    args = ast.literal_eval(spyder_args)
    reset = ast.literal_eval(reset)

    # Enforce the --new-instance flag when running spyder
    if '--new-instance' not in args:
        if is_bootstrap and '--' not in args:
            args = args + ['--', '--new-instance']
        else:
            args.append('--new-instance')

    # Create the arguments needed for reseting
    if '--' in args:
        args_reset = ['--', '--reset']
    else:
        args_reset = ['--reset']

    # Arrange arguments to be passed to the restarter and reset subprocess
    args = ' '.join(args)
    args_reset = ' '.join(args_reset)

    # Get python excutable running this script
    python = sys.executable

    # Build the command
    if is_bootstrap:
        spyder = osp.join(spyder_folder, 'bootstrap.py')
    else:
        spyderlib = osp.join(spyder_folder, 'spyderlib')
        spyder = osp.join(spyderlib, 'start_app.py')

    command = '"{0}" "{1}" {2}'.format(python, spyder, args)

    # Adjust the command and/or arguments to subprocess depending on the OS
    shell = not IS_WINDOWS

    # Before launching a new Spyder instance we need to make sure that the
    # previous one has closed. We wait for a fixed and "reasonable" amount of
    # time and check, otherwise an error is launched
    wait_time = 90 if IS_WINDOWS else 30  # Seconds
    for counter in range(int(wait_time / SLEEP_TIME)):
        if not is_pid_running(pid):
            break
        time.sleep(SLEEP_TIME)  # Throttling control
        QApplication.processEvents()  # Needed to refresh the splash
    else:
        # The old spyder instance took too long to close and restart aborts
        restarter.launch_error_message(error_type=CLOSE_ERROR)

    env = os.environ.copy()

    # Reset Spyder (if required)
    # -------------------------------------------------------------------------
    if reset:
        restarter.set_splash_message(_('Resetting Spyder to defaults'))
        command_reset = '"{0}" "{1}" {2}'.format(python, spyder, args_reset)

        try:
            p = subprocess.Popen(command_reset, shell=shell, env=env)
        except Exception as error:
            restarter.launch_error_message(error_type=RESET_ERROR, error=error)
        else:
            p.communicate()
            pid_reset = p.pid

        # Before launching a new Spyder instance we need to make sure that the
        # reset subprocess has closed. We wait for a fixed and "reasonable"
        # amount of time and check, otherwise an error is launched.
        wait_time = 20  # Seconds
        for counter in range(int(wait_time / SLEEP_TIME)):
            if not is_pid_running(pid_reset):
                break
            time.sleep(SLEEP_TIME)  # Throttling control
            QApplication.processEvents()  # Needed to refresh the splash
        else:
            # The reset subprocess took too long and it is killed
            try:
                p.kill()
            except OSError as error:
                restarter.launch_error_message(error_type=RESET_ERROR,
                                               error=error)
            else:
                restarter.launch_error_message(error_type=RESET_ERROR)

    # Restart
    # -------------------------------------------------------------------------
    restarter.set_splash_message(_('Restarting'))
    try:
        subprocess.Popen(command, shell=shell, env=env)
    except Exception as error:
        restarter.launch_error_message(error_type=RESTART_ERROR, error=error)
Example #47
0
    def oedit(obj, modal=True, namespace=None, keeper=objecteditor.DialogKeeper()):
        """
        Edit the object 'obj' in a GUI-based editor and return the edited copy
        (if Cancel is pressed, return None)

        The object 'obj' is a container
        
        Supported container types:
        dict, list, tuple, str/unicode or numpy.array
        
        (instantiate a new QApplication if necessary,
        so it can be called directly from the interpreter)
        """
        # Local import
        from spyderlib.widgets.texteditor import TextEditor
        from spyderlib.widgets.dicteditorutils import (ndarray, FakeObject,
                                                       Image, is_known_type)
        from spyderlib.widgets.dicteditor import DictEditor
        from spyderlib.widgets.arrayeditor import ArrayEditor
        
        from spyderlib.utils.qthelpers import qapplication
        app = qapplication()

        # STARTMODIFICATION EMZED
        import libms.Explorers
        from libms.DataStructures import PeakMap, Table
        # ENDMODIFICATION EMZED

        
        if modal:
            obj_name = ''
        else:
            assert isinstance(obj, basestring)
            obj_name = obj
            if namespace is None:
                namespace = globals()
            keeper.set_namespace(namespace)
            obj = namespace[obj_name]
            # keep QApplication reference alive in the Python interpreter:
            namespace['__qapp__'] = app

        conv_func = lambda data: data
        readonly = not is_known_type(obj)
        if isinstance(obj, ndarray) and ndarray is not FakeObject:
            dialog = ArrayEditor()
            if not dialog.setup_and_check(obj, title=obj_name,
                                          readonly=readonly):
                return
        elif isinstance(obj, Image) and Image is not FakeObject \
             and ndarray is not FakeObject:
            dialog = ArrayEditor()
            import numpy as np
            data = np.array(obj)
            if not dialog.setup_and_check(data, title=obj_name,
                                          readonly=readonly):
                return
            from spyderlib.pil_patch import Image
            conv_func = lambda data: Image.fromarray(data, mode=obj.mode)
        elif isinstance(obj, (str, unicode)):
            dialog = TextEditor(obj, title=obj_name, readonly=readonly)

        # START MODIFICATION EMZED
        elif isinstance(obj, PeakMap):
            dialog = libms.Explorers.MzExplorer()
            dialog.setup(obj)
        elif isinstance(obj, Table):
            dialog = libms.Explorers.TableExplorer([obj], False)
            conv_func = lambda (x,) : x
        elif isinstance(obj, list) and all(isinstance(t, Table) for t in obj):
            dialog = libms.Explorers.TableExplorer(obj, False)
        # END MODIFICATION EMZED

        else:
            dialog = DictEditor()
            dialog.setup(obj, title=obj_name, readonly=readonly)
        
        def end_func(dialog):
            return conv_func(dialog.get_value())
        
        if modal:
            if dialog.exec_():
                return end_func(dialog)
        else:
            keeper.create_dialog(dialog, obj_name, end_func)
            import os
            qt_inputhook = os.environ.get("INSTALL_QT_INPUTHOOK",
                                          "").lower() == "true"
            if os.name == 'nt' and not qt_inputhook \
               and not os.environ.get('IPYTHON', False):
                app.exec_()