def runcell(cellname, filename=None, is_pdb=False): """ Run a code cell from an editor as a file. Currently looks for code in an `ipython` property called `cell_code`. This property must be set by the editor prior to calling this function. This function deletes the contents of `cell_code` upon completion. Parameters ---------- cellname : str or int Cell name or index. filename : str Needed to allow for proper traceback links. """ if filename is None: filename = get_current_file_name() if filename is None: return try: filename = filename.decode('utf-8') except (UnicodeError, TypeError, AttributeError): # UnicodeError, TypeError --> eventually raised in Python 2 # AttributeError --> systematically raised in Python 3 pass ipython_shell = get_ipython() try: # Get code from spyder cell_code = _frontend_request().run_cell(cellname, filename) except Exception: _print("This command failed to be executed because an error occurred" " while trying to get the cell code from Spyder's" " editor. The error was:\n\n") get_ipython().showtraceback(exception_only=True) return if not cell_code: # Nothing to execute return # Trigger `post_execute` to exit the additional pre-execution. # See Spyder PR #7310. ipython_shell.events.trigger('post_execute') with NamespaceManager(filename, current_namespace=True) as namespace: try: if PY2: filename = maybe_encode(filename) exec(compile(cell_code, filename, 'exec'), namespace) except SystemExit as status: # ignore exit(0) if status.code: ipython_shell.showtraceback(exception_only=True) except BaseException as error: if isinstance(error, bdb.BdbQuit) and is_pdb: # Ignore BdbQuit if we are debugging, as it is expected. pass else: # We ignore the call to exec ipython_shell.showtraceback(tb_offset=1)
def runcell(cellname, filename=None, post_mortem=False): """ Run a code cell from an editor as a file. Currently looks for code in an `ipython` property called `cell_code`. This property must be set by the editor prior to calling this function. This function deletes the contents of `cell_code` upon completion. Parameters ---------- cellname : str or int Cell name or index. filename : str Needed to allow for proper traceback links. """ if filename is None: filename = get_current_file_name() if filename is None: return else: # get_debugger replaces \\ by / so we must undo that here # Otherwise code caching doesn't work if os.name == 'nt': filename = filename.replace('/', '\\') try: filename = filename.decode('utf-8') except (UnicodeError, TypeError, AttributeError): # UnicodeError, TypeError --> eventually raised in Python 2 # AttributeError --> systematically raised in Python 3 pass ipython_shell = get_ipython() try: # Get code from spyder cell_code = frontend_request().run_cell(cellname, filename) except Exception: _print("This command failed to be executed because an error occurred" " while trying to get the cell code from Spyder's" " editor. The error was:\n\n") get_ipython().showtraceback(exception_only=True) return if not cell_code or cell_code.strip() == '': _print("Nothing to execute, this cell is empty.\n") return # Trigger `post_execute` to exit the additional pre-execution. # See Spyder PR #7310. ipython_shell.events.trigger('post_execute') try: file_code = get_file_code(filename) except Exception: file_code = None with NamespaceManager(filename, current_namespace=True, file_code=file_code) as (ns_globals, ns_locals): exec_code(cell_code, filename, ns_globals, ns_locals, post_mortem=post_mortem)
def _exec_cell(cellname, filename=None, post_mortem=False, stack_depth=0, exec_fun=None, canonic_filename=None): """ Execute a code cell with a given exec function. """ # Tell IPython to hide this frame (>7.16) __tracebackhide__ = True if filename is None: filename = get_current_file_name() if filename is None: return ipython_shell = get_ipython() try: # Get code from spyder cell_code = frontend_request(blocking=True).run_cell( cellname, filename) except Exception: print("This command failed to be executed because an error occurred" " while trying to get the cell code from Spyder's" " editor. The error was:\n\n") get_ipython().showtraceback(exception_only=True) return if not cell_code or cell_code.strip() == '': print("Nothing to execute, this cell is empty.\n") return # Trigger `post_execute` to exit the additional pre-execution. # See Spyder PR #7310. ipython_shell.events.trigger('post_execute') file_code = get_file_code(filename, save_all=False) # Here the remote filename has been used. It must now be valid locally. if canonic_filename is not None: filename = canonic_filename else: # Normalise the filename filename = canonic(filename) with NamespaceManager(filename, current_namespace=True, file_code=file_code, stack_depth=stack_depth + 1) as (ns_globals, ns_locals): return exec_code(cell_code, filename, ns_globals, ns_locals, post_mortem=post_mortem, exec_fun=exec_fun, capture_last_expression=True)
def runfile(filename=None, args=None, wdir=None, namespace=None, post_mortem=False, current_namespace=False): """ Run filename args: command line arguments (string) wdir: working directory namespace: namespace for execution post_mortem: boolean, whether to enter post-mortem mode on error current_namespace: if true, run the file in the current namespace """ # Tell IPython to hide this frame (>7.16) __tracebackhide__ = True ipython_shell = get_ipython() if filename is None: filename = get_current_file_name() if filename is None: return else: # get_debugger replaces \\ by / so we must undo that here # Otherwise code caching doesn't work if os.name == 'nt': filename = filename.replace('/', '\\') try: filename = filename.decode('utf-8') except (UnicodeError, TypeError, AttributeError): # UnicodeError, TypeError --> eventually raised in Python 2 # AttributeError --> systematically raised in Python 3 pass if PY2: filename = encode(filename) if __umr__.enabled: __umr__.run() if args is not None and not isinstance(args, basestring): raise TypeError("expected a character buffer object") try: file_code = get_file_code(filename) except Exception: _print("This command failed to be executed because an error occurred" " while trying to get the file code from Spyder's" " editor. The error was:\n\n") get_ipython().showtraceback(exception_only=True) return if file_code is None: _print("Could not get code from editor.\n") return with NamespaceManager(filename, namespace, current_namespace, file_code=file_code) as (ns_globals, ns_locals): sys.argv = [filename] if args is not None: for arg in shlex.split(args): sys.argv.append(arg) if wdir is not None: if PY2: try: wdir = wdir.decode('utf-8') except (UnicodeError, TypeError): # UnicodeError, TypeError --> eventually raised in Python 2 pass if os.path.isdir(wdir): os.chdir(wdir) # See https://github.com/spyder-ide/spyder/issues/13632 if "multiprocessing.process" in sys.modules: try: import multiprocessing.process multiprocessing.process.ORIGINAL_DIR = os.path.abspath( wdir) except Exception: pass else: _print("Working directory {} doesn't exist.\n".format(wdir)) if __umr__.has_cython: # Cython files with io.open(filename, encoding='utf-8') as f: ipython_shell.run_cell_magic('cython', '', f.read()) else: exec_code(file_code, filename, ns_globals, ns_locals, post_mortem=post_mortem) sys.argv = ['']
def runfile(filename=None, args=None, wdir=None, namespace=None, post_mortem=False, is_pdb=False, current_namespace=False): """ Run filename args: command line arguments (string) wdir: working directory namespace: namespace for execution post_mortem: boolean, whether to enter post-mortem mode on error current_namespace: if true, run the file in the current namespace """ ipython_shell = get_ipython() if filename is None: filename = get_current_file_name() if filename is None: return try: # Save the open files _frontend_request().save_files() except Exception: logger.debug("Could not save files before executing.") try: filename = filename.decode('utf-8') except (UnicodeError, TypeError, AttributeError): # UnicodeError, TypeError --> eventually raised in Python 2 # AttributeError --> systematically raised in Python 3 pass if __umr__.enabled: __umr__.run() if args is not None and not isinstance(args, basestring): raise TypeError("expected a character buffer object") with NamespaceManager(filename, namespace, current_namespace) as namespace: sys.argv = [filename] if args is not None: for arg in shlex.split(args): sys.argv.append(arg) if wdir is not None: try: wdir = wdir.decode('utf-8') except (UnicodeError, TypeError, AttributeError): # UnicodeError, TypeError --> eventually raised in Python 2 # AttributeError --> systematically raised in Python 3 pass os.chdir(wdir) if post_mortem: set_post_mortem() if __umr__.has_cython: # Cython files with io.open(filename, encoding='utf-8') as f: ipython_shell.run_cell_magic('cython', '', f.read()) else: try: execfile(filename, namespace) except SystemExit as status: # ignore exit(0) if status.code: ipython_shell.showtraceback(exception_only=True) except BaseException as error: if isinstance(error, bdb.BdbQuit) and is_pdb: # Ignore BdbQuit if we are debugging, as it is expected. pass else: # We ignore the call to execfile and exec ipython_shell.showtraceback(tb_offset=2) clear_post_mortem() sys.argv = ['']
def _exec_cell(cellname, filename=None, post_mortem=False, stack_depth=0, exec_fun=None): """ Execute a code cell with a given exec function. """ # Tell IPython to hide this frame (>7.16) __tracebackhide__ = True if filename is None: filename = get_current_file_name() if filename is None: return else: # get_debugger replaces \\ by / so we must undo that here # Otherwise code caching doesn't work if os.name == 'nt': filename = filename.replace('/', '\\') try: filename = filename.decode('utf-8') except (UnicodeError, TypeError, AttributeError): # UnicodeError, TypeError --> eventually raised in Python 2 # AttributeError --> systematically raised in Python 3 pass ipython_shell = get_ipython() try: # Get code from spyder cell_code = frontend_request(blocking=True).run_cell( cellname, filename) except Exception: _print("This command failed to be executed because an error occurred" " while trying to get the cell code from Spyder's" " editor. The error was:\n\n") get_ipython().showtraceback(exception_only=True) return if not cell_code or cell_code.strip() == '': _print("Nothing to execute, this cell is empty.\n") return # Trigger `post_execute` to exit the additional pre-execution. # See Spyder PR #7310. ipython_shell.events.trigger('post_execute') try: file_code = get_file_code(filename, save_all=False) except Exception: file_code = None # Normalise the filename filename = os.path.abspath(filename) filename = os.path.normcase(filename) with NamespaceManager(filename, current_namespace=True, file_code=file_code, stack_depth=stack_depth + 1) as (ns_globals, ns_locals): return exec_code(cell_code, filename, ns_globals, ns_locals, post_mortem=post_mortem, exec_fun=exec_fun, capture_last_expression=True)
def _exec_file(filename=None, args=None, wdir=None, namespace=None, post_mortem=False, current_namespace=False, stack_depth=0, exec_fun=None, canonic_filename=None): # Tell IPython to hide this frame (>7.16) __tracebackhide__ = True ipython_shell = get_ipython() if filename is None: filename = get_current_file_name() if filename is None: return if __umr__.enabled: __umr__.run() if args is not None and not isinstance(args, str): raise TypeError("expected a character buffer object") try: file_code = get_file_code(filename, raise_exception=True) except Exception: print("This command failed to be executed because an error occurred" " while trying to get the file code from Spyder's" " editor. The error was:\n\n") get_ipython().showtraceback(exception_only=True) return # Here the remote filename has been used. It must now be valid locally. if canonic_filename is not None: filename = canonic_filename else: filename = canonic(filename) with NamespaceManager(filename, namespace, current_namespace, file_code=file_code, stack_depth=stack_depth + 1) as (ns_globals, ns_locals): sys.argv = [filename] if args is not None: for arg in shlex.split(args): sys.argv.append(arg) if "multiprocessing" in sys.modules: # See https://github.com/spyder-ide/spyder/issues/16696 try: sys.modules['__mp_main__'] = sys.modules['__main__'] except Exception: pass if wdir is not None: if os.path.isdir(wdir): os.chdir(wdir) # See https://github.com/spyder-ide/spyder/issues/13632 if "multiprocessing.process" in sys.modules: try: import multiprocessing.process multiprocessing.process.ORIGINAL_DIR = os.path.abspath( wdir) except Exception: pass else: print("Working directory {} doesn't exist.\n".format(wdir)) try: if __umr__.has_cython: # Cython files with io.open(filename, encoding='utf-8') as f: ipython_shell.run_cell_magic('cython', '', f.read()) else: exec_code(file_code, filename, ns_globals, ns_locals, post_mortem=post_mortem, exec_fun=exec_fun, capture_last_expression=False, global_warning=not current_namespace) finally: sys.argv = ['']