def restart(self, reset=False, close_immediately=False): """ Quit and Restart Spyder application. If reset True it allows to reset spyder on restart. """ # Get console plugin reference to call the quit action console = self.get_plugin(Plugins.Console) # Get start path to use in restart script spyder_start_directory = get_module_path('spyder') restart_script = osp.join(spyder_start_directory, 'app', 'restart.py') # Get any initial argument passed when spyder was started # Note: Variables defined in bootstrap.py and spyder/app/start.py env = os.environ.copy() bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None) spyder_args = env.pop('SPYDER_ARGS') # Get current process and python running spyder pid = os.getpid() python = sys.executable # Check if started with bootstrap.py if bootstrap_args is not None: spyder_args = bootstrap_args is_bootstrap = True else: is_bootstrap = False # Pass variables as environment variables (str) to restarter subprocess env['SPYDER_ARGS'] = spyder_args env['SPYDER_PID'] = str(pid) env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap) # Build the command and popen arguments depending on the OS if os.name == 'nt': # Hide flashing command prompt startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW shell = False else: startupinfo = None shell = True command = '"{0}" "{1}"' command = command.format(python, restart_script) try: if self.main.closing(True, close_immediately=close_immediately): subprocess.Popen(command, shell=shell, env=env, startupinfo=startupinfo) console.quit() except Exception as error: # If there is an error with subprocess, Spyder should not quit and # the error can be inspected in the internal console print(error) # spyder: test-skip print(command) # spyder: test-skip
def nbopen(filename, dark_theme=False): """ Open a notebook using the best available server. Returns information about the selected server. """ filename = osp.abspath(filename) home_dir = get_home_dir() server_info = find_best_server(filename) if server_info is not None: logger.debug('Using existing server at %s', server_info['notebook_dir']) return server_info else: if filename.startswith(home_dir): nbdir = home_dir else: nbdir = osp.dirname(filename) logger.debug("Starting new server") serverscript = osp.join(osp.dirname(__file__), '../server/main.py') command = [sys.executable, serverscript, '--no-browser', '--notebook-dir={}'.format(nbdir), '--NotebookApp.password='******'{}'".format( KERNELSPEC)] if dark_theme: command.append('--dark') if os.name == 'nt': creation_flag = 0x08000000 # CREATE_NO_WINDOW else: creation_flag = 0 # Default value if DEV: env = os.environ.copy() env["PYTHONPATH"] = osp.dirname(get_module_path('spyder')) subprocess.Popen(command, creationflags=creation_flag, env=env) else: subprocess.Popen(command, creationflags=creation_flag) # Wait ~25 secs for the server to be up for _x in range(100): server_info = find_best_server(filename) if server_info is not None: break else: time.sleep(0.25) if server_info is None: raise NBServerError() # Kill the server at exit atexit.register(notebookapp.shutdown_server, server_info, log=logger) return server_info
def start_server(self, filename, interpreter): """ Start a notebook server asynchronously. Start a server which can render the given notebook and return immediately. Assume the server uses the given interpreter. The manager will check periodically whether the server is accepting requests and emit `sig_server_started` or `sig_server_timed_out` when appropriate. Parameters ---------- filename : str File name of notebook to be rendered by the server. interpreter : str File name of Python interpreter to be used. """ home_dir = get_home_dir() if filename.startswith(home_dir): nbdir = home_dir else: nbdir = osp.dirname(filename) logger.debug('Starting new notebook server for %s', nbdir) process = QProcess(None) serverscript = osp.join(osp.dirname(__file__), '../server/main.py') serverscript = osp.normpath(serverscript) arguments = [ serverscript, '--no-browser', '--notebook-dir={}'.format(nbdir), '--NotebookApp.password='******'--KernelSpecManager.kernel_spec_class={}'.format(KERNELSPEC) ] if self.dark_theme: arguments.append('--dark') logger.debug('Arguments: %s', repr(arguments)) if DEV: env = QProcessEnvironment.systemEnvironment() env.insert('PYTHONPATH', osp.dirname(get_module_path('spyder'))) process.setProcessEnvironment(env) server_process = ServerProcess(process, notebook_dir=nbdir, interpreter=interpreter) process.setProcessChannelMode(QProcess.MergedChannels) process.readyReadStandardOutput.connect( lambda: self.read_server_output(server_process)) process.errorOccurred.connect( lambda error: self.handle_error(server_process, error)) process.finished.connect(lambda code, status: self.handle_finished( server_process, code, status)) process.start(sys.executable, arguments) self.servers.append(server_process) self._check_server_started(server_process)
def nbopen(filename): """ Open a notebook using the best available server. Returns information about the selected server. """ filename = osp.abspath(filename) home_dir = get_home_dir() server_info = find_best_server(filename) if server_info is not None: print("Using existing server at", server_info['notebook_dir']) return server_info else: if filename.startswith(home_dir): nbdir = home_dir else: nbdir = osp.dirname(filename) print("Starting new server") kernelspec = 'spyder.utils.ipython.kernelspec.SpyderKernelSpec' command = [ 'jupyter', 'notebook', '--no-browser', '--notebook-dir={}'.format(nbdir), '--NotebookApp.password='******'{}'".format(kernelspec) ] if os.name == 'nt': creation_flag = 0x08000000 # CREATE_NO_WINDOW else: creation_flag = 0 # Default value if DEV: env = os.environ.copy() env["PYTHONPATH"] = osp.dirname(get_module_path('spyder')) proc = subprocess.Popen(command, creationflags=creation_flag, env=env) else: proc = subprocess.Popen(command, creationflags=creation_flag) atexit.register(proc.terminate) # Wait ~10 secs for the server to be up for _x in range(40): server_info = find_best_server(filename) if server_info is not None: break else: time.sleep(0.25) if server_info is None: raise NBServerError() return server_info
def run(self): """Handle the connection with the server. """ # Set up the zmq port. self.socket = self.context.socket(zmq.PAIR) self.port = self.socket.bind_to_random_port('tcp://*') # Set up the process. self.process = QProcess(self) if self.cwd: self.process.setWorkingDirectory(self.cwd) p_args = ['-u', self.target, str(self.port)] if self.extra_args is not None: p_args += self.extra_args # Set up environment variables. processEnvironment = QProcessEnvironment() env = self.process.systemEnvironment() if (self.env and 'PYTHONPATH' not in self.env) or self.env is None: python_path = osp.dirname(get_module_path('spyder')) # Add the libs to the python path. for lib in self.libs: try: path = osp.dirname(imp.find_module(lib)[1]) python_path = osp.pathsep.join([python_path, path]) except ImportError: pass if self.extra_path: try: python_path = osp.pathsep.join([python_path] + self.extra_path) except Exception as e: debug_print("Error when adding extra_path to plugin env") debug_print(e) env.append("PYTHONPATH=%s" % python_path) if self.env: env.update(self.env) for envItem in env: envName, separator, envValue = envItem.partition('=') processEnvironment.insert(envName, envValue) self.process.setProcessEnvironment(processEnvironment) # Start the process and wait for started. self.process.start(self.executable, p_args) self.process.finished.connect(self._on_finished) running = self.process.waitForStarted() if not running: raise IOError('Could not start %s' % self) # Set up the socket notifer. fid = self.socket.getsockopt(zmq.FD) self.notifier = QSocketNotifier(fid, QSocketNotifier.Read, self) self.notifier.activated.connect(self._on_msg_received)
def run(self): """Handle the connection with the server. """ # Set up the zmq port. self.socket = self.context.socket(zmq.PAIR) self.port = self.socket.bind_to_random_port('tcp://*') # Set up the process. self.process = QProcess(self) if self.cwd: self.process.setWorkingDirectory(self.cwd) p_args = ['-u', self.target, str(self.port)] if self.extra_args is not None: p_args += self.extra_args # Set up environment variables. processEnvironment = QProcessEnvironment() env = self.process.systemEnvironment() if (self.env and 'PYTHONPATH' not in self.env) or self.env is None: python_path = osp.dirname(get_module_path('spyder')) # Add the libs to the python path. for lib in self.libs: try: path = osp.dirname(imp.find_module(lib)[1]) python_path = osp.pathsep.join([python_path, path]) except ImportError: pass env.append("PYTHONPATH=%s" % python_path) if self.env: env.update(self.env) for envItem in env: envName, separator, envValue = envItem.partition('=') processEnvironment.insert(envName, envValue) self.process.setProcessEnvironment(processEnvironment) # Start the process and wait for started. self.process.start(self.executable, p_args) self.process.finished.connect(self._on_finished) running = self.process.waitForStarted() if not running: raise IOError('Could not start %s' % self) # Set up the socket notifer. fid = self.socket.getsockopt(zmq.FD) self.notifier = QSocketNotifier(fid, QSocketNotifier.Read, self) self.notifier.activated.connect(self._on_msg_received)
def nbopen(filename): """ Open a notebook using the best available server. Returns information about the selected server. """ filename = osp.abspath(filename) home_dir = get_home_dir() server_info = find_best_server(filename) if server_info is not None: print("Using existing server at", server_info['notebook_dir']) return server_info else: if filename.startswith(home_dir): nbdir = home_dir else: nbdir = osp.dirname(filename) print("Starting new server") kernelspec = 'spyder.utils.ipython.kernelspec.SpyderKernelSpec' command = ['jupyter', 'notebook', '--no-browser', '--notebook-dir={}'.format(nbdir), '--NotebookApp.password='******'{}'".format( kernelspec)] if os.name == 'nt': creation_flag = 0x08000000 # CREATE_NO_WINDOW else: creation_flag = 0 # Default value if DEV: env = os.environ.copy() env["PYTHONPATH"] = osp.dirname(get_module_path('spyder')) proc = subprocess.Popen(command, creationflags=creation_flag, env=env) else: proc = subprocess.Popen(command, creationflags=creation_flag) # Kill the server at exit. We need to use psutil for this because # Popen.terminate doesn't work when creationflags or shell=True # are used. def kill_server_and_childs(pid): ps_proc = psutil.Process(pid) for child in ps_proc.children(recursive=True): child.kill() ps_proc.kill() atexit.register(kill_server_and_childs, proc.pid) # Wait ~25 secs for the server to be up for _x in range(100): server_info = find_best_server(filename) if server_info is not None: break else: time.sleep(0.25) if server_info is None: raise NBServerError() return server_info