def exec_code(code, filename, ns_globals, ns_locals=None): """Execute code and display any exception.""" if PY2: filename = encode(filename) code = encode(code) ipython_shell = get_ipython() is_ipython = os.path.splitext(filename)[1] == '.ipy' try: if is_ipython: # transform code tm = TransformerManager() if not PY2: # Avoid removing lines tm.cleanup_transforms = [] code = tm.transform_cell(code) exec(compile(code, filename, 'exec'), ns_globals, ns_locals) 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 ipython_shell.kernel._pdb_obj): # Ignore BdbQuit if we are debugging, as it is expected. ipython_shell.kernel._pdb_obj = None else: # We ignore the call to exec ipython_shell.showtraceback(tb_offset=1)
def exec_code(code, filename, ns_globals, ns_locals=None, post_mortem=False): """Execute code and display any exception.""" # Tell IPython to hide this frame (>7.16) __tracebackhide__ = True global SHOW_INVALID_SYNTAX_MSG if PY2: filename = encode(filename) code = encode(code) ipython_shell = get_ipython() is_ipython = os.path.splitext(filename)[1] == '.ipy' try: if not is_ipython: # TODO: remove the try-except and let the SyntaxError raise # Because there should not be ipython code in a python file try: compiled = compile( transform_cell(code, indent_only=True), filename, 'exec') except SyntaxError as e: try: compiled = compile(transform_cell(code), filename, 'exec') except SyntaxError: if PY2: raise e else: # Need to call exec to avoid Syntax Error in Python 2. # TODO: remove exec when dropping Python 2 support. exec("raise e from None") else: if SHOW_INVALID_SYNTAX_MSG: _print( "\nWARNING: This is not valid Python code. " "If you want to use IPython magics, " "flexible indentation, and prompt removal, " "we recommend that you save this file with the " ".ipy extension.\n") SHOW_INVALID_SYNTAX_MSG = False else: compiled = compile(transform_cell(code), filename, 'exec') exec(compiled, ns_globals, ns_locals) 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 ipython_shell.kernel._pdb_obj): # Ignore BdbQuit if we are debugging, as it is expected. ipython_shell.kernel._pdb_obj = None elif post_mortem and isinstance(error, Exception): error_type, error, tb = sys.exc_info() post_mortem_excepthook(error_type, error, tb) else: # We ignore the call to exec ipython_shell.showtraceback(tb_offset=1) __tracebackhide__ = "__pdb_exit__"
def exec_code(code, filename, ns_globals, ns_locals=None): """Execute code and display any exception.""" global SHOW_INVALID_SYNTAX_MSG if PY2: filename = encode(filename) code = encode(code) ipython_shell = get_ipython() is_ipython = os.path.splitext(filename)[1] == '.ipy' try: if not is_ipython: # TODO: remove the try-except and let the SyntaxError raise # Because there should not be ipython code in a python file try: compiled = compile(code, filename, 'exec') except SyntaxError as e: try: compiled = compile(transform_cell(code), filename, 'exec') except SyntaxError: if PY2: raise e else: # Need to call exec to avoid Syntax Error in Python 2. # TODO: remove exec when dropping Python 2 support. exec("raise e from None") else: if SHOW_INVALID_SYNTAX_MSG: _print( "\nWARNING: This is not valid Python code. " "If you want to use IPython magics, " "flexible indentation, and prompt removal, " "please save this file with the .ipy extension. " "This will be an error in a future version of " "Spyder.\n") SHOW_INVALID_SYNTAX_MSG = False else: compiled = compile(transform_cell(code), filename, 'exec') exec(compiled, ns_globals, ns_locals) 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 ipython_shell.kernel._pdb_obj): # Ignore BdbQuit if we are debugging, as it is expected. ipython_shell.kernel._pdb_obj = None else: # We ignore the call to exec ipython_shell.showtraceback(tb_offset=1)
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 = ['']