def setup_editor(qtbot, monkeypatch): """Set up the Editor plugin.""" qapplication() from spyder.plugins.editor.plugin import Editor monkeypatch.setattr('spyder.plugins.editor.plugin.add_actions', Mock()) class MainMock(QWidget): def __getattr__(self, attr): if attr.endswith('actions'): return [] elif attr == 'projects': projects = Mock() projects.get_active_project.return_value = None return projects else: return Mock() def get_spyder_pythonpath(*args): return [] editor = Editor(MainMock()) qtbot.addWidget(editor) editor.show() yield editor, qtbot
def test(text): """Test""" from spyder.utils.qthelpers import qapplication _app = qapplication() # analysis:ignore dialog = ImportWizard(None, text) if dialog.exec_(): print(dialog.get_data())
def construct_editor(qtbot, *args, **kwargs): os.environ['SPY_TEST_USE_INTROSPECTION'] = 'True' app = qapplication() lsp_manager = LSPManager(parent=None) editor = CodeEditor(parent=None) kwargs['language'] = 'Python' editor.setup_editor(*args, **kwargs) wrapper = LSPEditorWrapper(None, editor, lsp_manager) lsp_manager.register_plugin_type( LSPEventTypes.DOCUMENT, wrapper.sig_initialize) with qtbot.waitSignal(wrapper.sig_initialize, timeout=30000): editor.filename = 'test.py' editor.language = 'Python' lsp_manager.start_lsp_client('python') text = ("def some_function():\n" # D100, D103: Missing docstring " \n" # W293 trailing spaces " a = 1 # a comment\n" # E261 two spaces before inline comment "\n" " a += s\n" # Undefined variable s " return a\n" ) editor.set_text(text) with qtbot.waitSignal(editor.lsp_response_signal, timeout=30000): editor.document_did_open() yield editor, lsp_manager os.environ['SPY_TEST_USE_INTROSPECTION'] = 'False' lsp_manager.closing_plugin()
def test(): """Run history widget.""" from spyder.utils.qthelpers import qapplication app = qapplication(test_time=8) widget = History(None) widget.show() sys.exit(app.exec_())
def test(): from spyder.utils.qthelpers import qapplication app = qapplication() test = ProjectExplorerTest() test.resize(250, 480) test.show() app.exec_()
def setup_editor(qtbot, monkeypatch): """Set up the Editor plugin.""" app = qapplication() os.environ['SPY_TEST_USE_INTROSPECTION'] = 'True' monkeypatch.setattr('spyder.dependencies', Mock()) from spyder.plugins.editor import Editor monkeypatch.setattr('spyder.plugins.editor.add_actions', Mock()) class MainMock(QWidget): def __getattr__(self, attr): if attr.endswith('actions'): return [] else: return Mock() def get_spyder_pythonpath(*args): return [] editor = Editor(MainMock()) qtbot.addWidget(editor) editor.show() editor.new(fname="test.py", text="") editor.introspector.set_editor_widget(editor.editorstacks[0]) yield editor, qtbot # teardown os.environ['SPY_TEST_USE_INTROSPECTION'] = 'False' editor.introspector.plugin_manager.close()
def test(): """Local test.""" from spyder.utils.qthelpers import qapplication app = qapplication() dlg = ProjectDialog(None) dlg.show() sys.exit(app.exec_())
def test(): """Run breakpoint widget test""" from spyder.utils.qthelpers import qapplication app = qapplication() widget = BreakpointWidget(None) widget.show() sys.exit(app.exec_())
def test(): # pragma: no cover from spyder.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_()
def test(): from spyder.utils.qthelpers import qapplication app = qapplication() table = ShortcutsTable() table.show() app.exec_() table.check_shortcuts()
def test(): from spyder.utils.qthelpers import qapplication app = qapplication() table = ShortcutsTable() table.show() app.exec_() print([str(s) for s in table.source_model.shortcuts]) # spyder: test-skip table.check_shortcuts()
def test(): """Run Find in Files widget test""" from spyder.utils.qthelpers import qapplication app = qapplication() widget = FindInFilesWidget(None) widget.resize(640, 480) widget.show() sys.exit(app.exec_())
def test(): """Run path manager test""" from spyder.utils.qthelpers import qapplication _app = qapplication() # analysis:ignore test = PathManager(None, pathlist=sys.path[:-10], ro_pathlist=sys.path[-10:]) test.exec_() print(test.get_path_list()) # spyder: test-skip
def test(): """Run web browser""" from spyder.utils.qthelpers import qapplication app = qapplication(test_time=8) widget = PydocBrowser(None) widget.show() widget.initialize() sys.exit(app.exec_())
def test(): """Run web browser""" from spyder.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_())
def test(): """Run widget test""" from spyder.utils.qthelpers import qapplication app = qapplication() widget = UnitTestingWidget(None) widget.resize(800, 600) widget.show() widget.analyze(osp.normpath(osp.join(osp.dirname(__file__), osp.pardir))) sys.exit(app.exec_())
def test(): """Run pylint widget test""" from spyder.utils.qthelpers import qapplication app = qapplication(test_time=20) widget = PylintWidget(None) widget.resize(640, 480) widget.show() widget.analyze(__file__) sys.exit(app.exec_())
def editor_close_quotes(): """Set up Editor with close quotes activated.""" app = qapplication() editor = CodeEditor(parent=None) kwargs = {} kwargs['language'] = 'Python' kwargs['close_quotes'] = True editor.setup_editor(**kwargs) return editor
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
def editor_auto_docstring(): """Set up Editor with auto docstring activated.""" app = qapplication() editor = CodeEditor(parent=None) kwargs = {} kwargs['language'] = 'Python' kwargs['close_quotes'] = True kwargs['close_parentheses'] = True editor.setup_editor(**kwargs) return editor
def main(): """Run Windows environment variable editor""" from spyder.utils.qthelpers import qapplication app = qapplication() if os.name == 'nt': dialog = WinUserEnvDialog() else: dialog = EnvDialog() dialog.show() app.exec_()
def test(file_explorer): from spyder.utils.qthelpers import qapplication app = qapplication() if file_explorer: test = FileExplorerTest() else: test = ProjectExplorerTest() test.resize(640, 480) test.show() app.exec_()
def test(): """Run widget test""" from spyder.utils.qthelpers import qapplication app = qapplication() widget = LineProfilerWidget(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_())
def test_msgcheckbox(): from spyder.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_()
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)
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())
def test(): """Text editor demo""" from spyder.utils.qthelpers import qapplication _app = qapplication() # analysis:ignore text = """01234567890123456789012345678901234567890123456789012345678901234567890123456789 dedekdh elkd ezd ekjd lekdj elkdfjelfjk e""" dialog = TextEditor(text) dialog.exec_() dlg_text = dialog.get_value() assert text == dlg_text
def test(): """Test LSP client.""" from spyder.utils.qthelpers import qapplication app = qapplication(test_time=8) server_args_fmt = '--host %(host)s --port %(port)s --tcp' server_settings = {'host': '127.0.0.1', 'port': 2087, 'cmd': 'pyls'} lsp = LSPClient(app, server_args_fmt, server_settings) lsp.start() app.aboutToQuit.connect(lsp.stop) signal.signal(signal.SIGINT, signal.SIG_DFL) sys.exit(app.exec_())
def setup_editor(qtbot, monkeypatch, tmpdir_factory): """Set up the Editor plugin.""" qapplication() from spyder.plugins.editor.plugin import Editor monkeypatch.setattr('spyder.plugins.editor.plugin.add_actions', Mock()) class MainMock(QMainWindow): def __getattr__(self, attr): if attr.endswith('actions'): return [] elif attr == 'projects': projects = Mock() projects.get_active_project.return_value = None return projects else: return Mock() window = MainMock() editor = Editor(window) expected_filenames, tmpdir = python_files(tmpdir_factory) def get_option(option, default=None): splitsettings = [(False, osp.join(tmpdir, 'file1.py'), [1, 1, 1, 1])] return {'layout_settings': {'splitsettings': splitsettings}, 'filenames': expected_filenames, 'max_recent_files': 20 }.get(option) editor.get_option = get_option editor.setup_open_files() window.setCentralWidget(editor) window.resize(640, 480) qtbot.addWidget(window) window.show() yield editor
def test(): """Run layout test widget test""" from spyder.utils.qthelpers import qapplication app = qapplication() names = ['test', 'tester', '20', '30', '40'] order = ['test', 'tester', '20', '30', '40'] active = ['test', 'tester'] widget_1 = LayoutSettingsDialog(None, names, order, active) widget_2 = LayoutSaveDialog(None, order) widget_1.show() widget_2.show() sys.exit(app.exec_())
def construct_editor(*args, **kwargs): app = qapplication() editor = CodeEditor(parent=None) kwargs['language'] = 'Python' editor.setup_editor(*args, **kwargs) text = ( "def some_function():\n" " \n" # W293 trailing spaces " a = 1 # a comment\n" # E261 two spaces before inline comment "\n" " a += s\n" # Undefined variable s " return a\n") editor.set_text(text) source_code = to_binary_string(editor.toPlainText()) results = check_with_pyflakes(source_code) + check_with_pep8(source_code) editor.process_code_analysis(results) return editor
def test_get_settings(monkeypatch): def mock_get_option(self, option): if option == 'remote1': return 'remote1val' if option == 'remote2': return 'remote2val' if option == 'dataframe_format': return '3d' monkeypatch.setattr(VariableExplorer, 'CONF_SECTION', 'sect') monkeypatch.setattr('spyder.plugins.variableexplorer.REMOTE_SETTINGS', ['remote1', 'remote2']) monkeypatch.setattr(VariableExplorer, 'get_option', mock_get_option) app = qapplication() settings = VariableExplorer(None).get_settings() expected = { 'remote1': 'remote1val', 'remote2': 'remote2val', 'dataframe_format': '%3d' } assert settings == expected
def test(): """Run widget test""" import inspect import tempfile from spyder.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_())
def test(): """Local test.""" from spyder.utils.qthelpers import qapplication from spyder.plugins.projects.api import BaseProjectType class MockProjectType(BaseProjectType): @staticmethod def get_name(): return "Boo" @staticmethod def validate_name(path, name): return False, "BOOM!" app = qapplication() dlg = ProjectDialog(None, {"empty": MockProjectType}) dlg.show() sys.exit(app.exec_())
def test(): """Run dependency widget test""" from spyder import dependencies # Test sample dependencies.add("IPython", "Enhanced Python interpreter", ">=20.0") dependencies.add("matplotlib", "Interactive data plotting", ">=1.0") dependencies.add("sympy", "Symbolic Mathematics", ">=10.0", optional=True) dependencies.add("foo", "Non-existent module", ">=1.0") dependencies.add("numpy", "Edit arrays in Variable Explorer", ">=0.10", optional=True) from spyder.utils.qthelpers import qapplication app = qapplication() dlg = DependenciesDialog(None) dlg.set_data(dependencies.DEPENDENCIES) dlg.show() sys.exit(dlg.exec_())
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 spyder.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 if os.name == 'nt': app.exec_()
def setup_editor(qtbot, monkeypatch): """Set up the Editor plugin.""" app = qapplication() os.environ['SPY_TEST_USE_INTROSPECTION'] = 'True' monkeypatch.setattr('spyder.dependencies', Mock()) from spyder.plugins.editor.plugin import Editor monkeypatch.setattr('spyder.plugins.editor.plugin.add_actions', Mock()) class MainMock(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) self.lspmanager = LSPManager(parent=self) self.projects = None def __getattr__(self, attr): if attr.endswith('actions'): return [] if attr == 'lspmanager': return self.lspmanager else: return Mock() def get_spyder_pythonpath(*args): return [] editor = Editor(MainMock(None)) editor.register_plugin() qtbot.addWidget(editor) editor.show() with qtbot.waitSignal(editor.sig_lsp_notification, timeout=30000): editor.new(fname="test.py", text="") # editor.introspector.set_editor_widget(editor.editorstacks[0]) code_editor = editor.get_focus_widget() with qtbot.waitSignal(code_editor.lsp_response_signal, timeout=30000): code_editor.document_did_open() yield editor, qtbot # teardown os.environ['SPY_TEST_USE_INTROSPECTION'] = 'False' editor.main.lspmanager.shutdown()
def run_test(): # Third party imports from qtpy.QtWidgets import QHBoxLayout, QTableWidget, QMainWindow # Local imports from spyder.utils.qthelpers import qapplication app = qapplication() main = QMainWindow() widget = PluginMainWidget('test', main) widget.get_title = lambda x=None: 'Test title' widget._setup() layout = QHBoxLayout() layout.addWidget(QTableWidget()) widget.setLayout(layout) widget.start_spinner() dock, location = widget.create_dockwidget(main) main.addDockWidget(location, dock) main.setStyleSheet(str(APP_STYLESHEET)) main.show() app.exec_()
def get_indent_fix(text, indent_chars=" " * 4, tab_stop_width_spaces=4, sol=False): """Return text with last line's indentation fixed.""" app = qapplication() editor = CodeEditor(parent=None) editor.setup_editor(language='Python', indent_chars=indent_chars, tab_stop_width_spaces=tab_stop_width_spaces) editor.set_text(text) cursor = editor.textCursor() cursor.movePosition(QTextCursor.End) if sol: lines = text.splitlines(True) repeat = len(lines[-1].lstrip()) cursor.movePosition(QTextCursor.Left, n=repeat) editor.setTextCursor(cursor) editor.fix_indent() return to_text_string(editor.toPlainText())
def preview_layout(self, show_hidden_areas=False): """ Show the layout with placeholder texts using a QWidget. """ from spyder.utils.qthelpers import qapplication app = qapplication() widget = QWidget() layout = QGridLayout() for area in self._areas: label = QPlainTextEdit() label.setReadOnly(True) label.setPlainText("\n".join(area["plugin_ids"])) if area["visible"] or show_hidden_areas: layout.addWidget( label, area["row"], area["column"], area["row_span"], area["col_span"], ) # label.setVisible(area["visible"]) if area["default"]: label.setStyleSheet( "QPlainTextEdit {background-color: #ff0000;}") if not area["visible"]: label.setStyleSheet( "QPlainTextEdit {background-color: #eeeeee;}") for row, stretch in self._row_stretchs.items(): layout.setRowStretch(row, stretch) for col, stretch in self._column_stretchs.items(): layout.setColumnStretch(col, stretch) widget.setLayout(layout) widget.showMaximized() app.exec_()
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_CI_WIDGETS', None) if test_travis is not None: from spyder.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()
def test(): """Run object editor test""" import datetime import numpy as np from spyder.pil_patch import Image app = qapplication() data = np.random.random_integers(255, size=(100, 100)).astype('uint8') image = Image.fromarray(data) class Foobar(object): def __init__(self): self.text = "toto" def get_text(self): return self.text foobar = Foobar() example = { 'str': 'kjkj kj k j j kj k jkj', 'list': [1, 3, 4, 'kjkj', None], 'set': {1, 2, 1, 3, None, 'A', 'B', 'C', True, False}, 'dict': { 'd': 1, 'a': np.random.rand(10, 10), 'b': [1, 2] }, 'float': 1.2233, 'array': np.random.rand(10, 10), 'image': image, 'date': datetime.date(1945, 5, 8), 'datetime': datetime.datetime(1945, 5, 8), 'foobar': foobar } ObjectExplorer.create_explorer(example, 'Example', show_callable_attributes=True, show_special_attributes=True)
def test(): """ Run widget test. Show the unittest widgets, configured so that our own tests are run when the user clicks "Run tests". """ from spyder.utils.qthelpers import qapplication app = qapplication() widget = UnitTestWidget(None) # set wdir to .../spyder_unittest wdir = osp.abspath(osp.join(osp.dirname(__file__), osp.pardir)) widget.config = Config('pytest', wdir) # add wdir's parent to python path, so that `import spyder_unittest` works rootdir = osp.abspath(osp.join(wdir, osp.pardir)) widget.pythonpath = [rootdir] widget.resize(800, 600) widget.show() sys.exit(app.exec_())
def local_test(): # pragma: no cover """Main local test.""" from spyder.utils.qthelpers import qapplication app = qapplication() wm = WorkerManager(max_threads=3) for i in range(7): worker = wm.create_python_worker(sleeping_func, 'BOOM! {}'.format(i), secs=5) worker.sig_finished.connect(ready_print) worker.start() worker = wm.create_python_worker(sleeping_func, 'BOOM!', secs=5) worker.sig_finished.connect(ready_print) worker.start() worker = wm.create_process_worker(['conda', 'info', '--json']) worker.sig_finished.connect(ready_print) worker.start() # wm.terminate_all() # wm.terminate_all() sys.exit(app.exec_())
def get_fold_levels(): """setup editor and return fold levels.""" app = qapplication() editor = CodeEditor(parent=None) editor.setup_editor(language='Python') text = ( '# dummy test file\n' 'class a():\n' # fold-block level-0 ' self.b = 1\n' ' print(self.b)\n' ' \n' ' def some_method(self):\n' # fold-block level-1 ' self.b = 3\n' '\n' ' def other_method(self):\n' # fold-block level-1 ' a = (1,\n' # fold-block level-2 ' 2,\n' ' 3)\n') editor.set_text(text) return print_tree(editor, return_list=True)
def test(): from spyder.utils.qthelpers import qapplication app = qapplication() from spyder.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 spyder.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_())
def test(): """Run object editor test""" # Local import from spyder.utils.qthelpers import qapplication app = qapplication() # analysis:ignore data = np.random.randint(1, 256, size=(100, 100)).astype('uint8') image = PIL.Image.fromarray(data) example = { 'str': 'kjkj kj k j j kj k jkj', 'list': [1, 3, 4, 'kjkj', None], 'set': {1, 2, 1, 3, None, 'A', 'B', 'C', True, False}, 'dict': { 'd': 1, 'a': np.random.rand(10, 10), 'b': [1, 2] }, 'float': 1.2233, 'array': np.random.rand(10, 10), 'image': image, 'date': datetime.date(1945, 5, 8), 'datetime': datetime.datetime(1945, 5, 8), } image = oedit(image) class Foobar(object): def __init__(self): self.text = "toto" foobar = Foobar() print(oedit(foobar, app=app)) # spyder: test-skip print(oedit(example, app=app)) # spyder: test-skip print(oedit(np.random.rand(10, 10), app=app)) # spyder: test-skip print(oedit(oedit.__doc__, app=app)) # spyder: test-skip print(example) # spyder: test-skip
def test(main=None): # pragma: no cover """Launch the switcher with some test values.""" from spyder.utils.qthelpers import qapplication app = qapplication() create_example_switcher(main=main) app.exec_()
def main(): #========================================================================== # Proper high DPI scaling is available in Qt >= 5.6.0. This attibute must # be set before creating the application. #========================================================================== if CONF.get('main', 'high_dpi_custom_scale_factor'): factors = str(CONF.get('main', 'high_dpi_custom_scale_factors')) f = list(filter(None, factors.split(';'))) if len(f) == 1: os.environ['QT_SCALE_FACTOR'] = f[0] else: os.environ['QT_SCREEN_SCALE_FACTORS'] = factors else: os.environ['QT_SCALE_FACTOR'] = '' os.environ['QT_SCREEN_SCALE_FACTORS'] = '' # Splash screen # ------------------------------------------------------------------------- # Start Qt Splash to inform the user of the current status app = qapplication() restarter = Restarter() if PYQT5: APP_ICON = QIcon(get_image_path("spyder.svg")) else: APP_ICON = QIcon(get_image_path("spyder.png")) app.setWindowIcon(APP_ICON) restarter.set_splash_message(_('Closing Spyder')) # Get variables # Note: Variables defined in app/mainwindow.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 this_folder = osp.split(osp.dirname(osp.abspath(__file__)))[0] spyder_folder = osp.split(this_folder)[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: spyderdir = osp.join(spyder_folder, 'spyder') spyder = osp.join(spyderdir, 'app', 'start.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)
def test(): from spyder.utils.qthelpers import qapplication app = qapplication() widget = FindInFiles() widget.show() sys.exit(app.exec_())
def construct_editor(*args, **kwargs): app = qapplication() editor = CodeEditor(parent=None) kwargs['language'] = 'Python' editor.setup_editor(*args, **kwargs) return editor
def test(): from spyder.utils.qthelpers import qapplication app = qapplication() dlg = SpyderErrorDialog() dlg.show() sys.exit(dlg.exec_())
prev_text = '' text = block.text().strip() if text in self.open_chars: return TextBlockHelper.get_fold_lvl(prev_block) + 1 if prev_text.endswith(self.open_chars) and prev_text not in \ self.open_chars: return TextBlockHelper.get_fold_lvl(prev_block) + 1 if self.close_chars in prev_text: return TextBlockHelper.get_fold_lvl(prev_block) - 1 return TextBlockHelper.get_fold_lvl(prev_block) if __name__ == '__main__': """Print folding blocks of this file for debugging""" from spyder.plugins.editor.api.folding import print_tree from spyder.utils.qthelpers import qapplication from spyder.plugins.editor.widgets.codeeditor import CodeEditor if len(sys.argv) > 1: fname = sys.argv[1] else: fname = __file__ app = qapplication() editor = CodeEditor(parent=None) editor.setup_editor(language='Python') editor.set_text_from_file(fname) print_tree(editor)
# (see LICENSE.txt for details) """Tests for memoryprofiler.py.""" from __future__ import division # Standard library imports import os import sys # Third party imports import pytest from pytestqt import qtbot from qtpy.QtCore import Qt from spyder.utils.qthelpers import qapplication MAIN_APP = qapplication() # Local imports from spyder_memory_profiler.widgets.memoryprofiler import MemoryProfilerWidget try: from unittest.mock import Mock except ImportError: from mock import Mock # Python 2 TEST_SCRIPT = \ """@profile def foo(): a = [1] * (10 ** 6) b = [2] * (2 * 10 ** 7)
def test(): from spyder.utils.qthelpers import qapplication app = qapplication() dlg = DlgGitHubLogin(None, None) dlg.show() sys.exit(dlg.exec_())
def test(): # pragma: no cover from spyder.utils.qthelpers import qapplication app = qapplication() dlg_shortcuts = ShortcutsSummaryDialog(None) dlg_shortcuts.show() app.exec_()