def run_file(file, globals=None, locals=None, is_module=False):
    module_name = None
    entry_point_fn = None
    if is_module:
        file, _, entry_point_fn = file.partition(':')
        module_name = file
        filename = get_fullname(file)
        if filename is None:
            sys.stderr.write("No module named %s\n" % file)
            return
        else:
            file = filename

    if os.path.isdir(file):
        new_target = os.path.join(file, '__main__.py')
        if os.path.isfile(new_target):
            file = new_target

    if globals is None:
        m = save_main_module(file, 'pydev_run_in_console')

        globals = m.__dict__
        try:
            globals['__builtins__'] = __builtins__
        except NameError:
            pass  # Not there on Jython...

    if locals is None:
        locals = globals

    if not is_module:
        sys.path.insert(0, os.path.split(file)[0])

    print('Running %s' % file)
    try:
        if not is_module:
            pydev_imports.execfile(file, globals, locals)  # execute the script
        else:
            # treat ':' as a seperator between module and entry point function
            # if there is no entry point we run we same as with -m switch. Otherwise we perform
            # an import and execute the entry point
            if entry_point_fn:
                mod = __import__(module_name,
                                 level=0,
                                 fromlist=[entry_point_fn],
                                 globals=globals,
                                 locals=locals)
                func = getattr(mod, entry_point_fn)
                func()
            else:
                # Run with the -m switch
                import runpy
                if hasattr(runpy, '_run_module_as_main'):
                    runpy._run_module_as_main(module_name)
                else:
                    runpy.run_module(module_name)
    except:
        traceback.print_exc()

    return globals
Ejemplo n.º 2
0
def run_file(file, globals=None, locals=None):
    if os.path.isdir(file):
        new_target = os.path.join(file, '__main__.py')
        if os.path.isfile(new_target):
            file = new_target

    if globals is None:
        m = save_main_module(file, 'pydev_run_in_console')

        globals = m.__dict__
        try:
            globals['__builtins__'] = __builtins__
        except NameError:
            pass  # Not there on Jython...

    if locals is None:
        locals = globals

    sys.path.insert(0, os.path.split(file)[0])

    print('Running %s' % file)
    try:
        pydev_imports.execfile(file, globals, locals)  # execute the script
    except:
        traceback.print_exc()

    return globals
def run_file(file, globals=None, locals=None, is_module=False):
    module_name = None
    entry_point_fn = None
    if is_module:
        file, _,  entry_point_fn = file.partition(':')
        module_name = file
        filename = get_fullname(file)
        if filename is None:
            sys.stderr.write("No module named %s\n" % file)
            return
        else:
            file = filename

    if os.path.isdir(file):
        new_target = os.path.join(file, '__main__.py')
        if os.path.isfile(new_target):
            file = new_target

    if globals is None:
        m = save_main_module(file, 'pydev_run_in_console')

        globals = m.__dict__
        try:
            globals['__builtins__'] = __builtins__
        except NameError:
            pass  # Not there on Jython...

    if locals is None:
        locals = globals

    if not is_module:
        sys.path.insert(0, os.path.split(file)[0])

    print('Running %s' % file)
    try:
        if not is_module:
            pydev_imports.execfile(file, globals, locals)  # execute the script
        else:
            # treat ':' as a seperator between module and entry point function
            # if there is no entry point we run we same as with -m switch. Otherwise we perform
            # an import and execute the entry point
            if entry_point_fn:
                mod = __import__(module_name, level=0, fromlist=[entry_point_fn], globals=globals, locals=locals)
                func = getattr(mod, entry_point_fn)
                func()
            else:
                # Run with the -m switch
                import runpy
                if hasattr(runpy, '_run_module_as_main'):
                    runpy._run_module_as_main(module_name)
                else:
                    runpy.run_module(module_name)
    except:
        traceback.print_exc()

    return globals
Ejemplo n.º 4
0
    def apply(self):
        mod = self.mod
        self._on_finish_callbacks = []
        try:
            # Get the module namespace (dict) early; this is part of the type check
            modns = mod.__dict__

            # Execute the code.  We copy the module dict to a temporary; then
            # clear the module dict; then execute the new code in the module
            # dict; then swap things back and around.  This trick (due to
            # Glyph Lefkowitz) ensures that the (readonly) __globals__
            # attribute of methods and functions is set to the correct dict
            # object.
            new_namespace = modns.copy()
            new_namespace.clear()
            if self.mod_filename:
                new_namespace["__file__"] = self.mod_filename
                try:
                    new_namespace["__builtins__"] = __builtins__
                except NameError:
                    raise  # Ok if not there.

            if self.mod_name:
                new_namespace["__name__"] = self.mod_name
                if new_namespace["__name__"] == '__main__':
                    # We do this because usually the __main__ starts-up the program, guarded by
                    # the if __name__ == '__main__', but we don't want to start the program again
                    # on a reload.
                    new_namespace["__name__"] = '__main_reloaded__'

            execfile(self.mod_filename, new_namespace, new_namespace)
            # Now we get to the hard part
            oldnames = set(modns)
            newnames = set(new_namespace)

            # Create new tokens (note: not deleting existing)
            for name in newnames - oldnames:
                notify_info0('Added:', name, 'to namespace')
                self.found_change = True
                modns[name] = new_namespace[name]

            # Update in-place what we can
            for name in oldnames & newnames:
                self._update(modns, name, modns[name], new_namespace[name])

            self._handle_namespace(modns)

            for c in self._on_finish_callbacks:
                c()
            del self._on_finish_callbacks[:]
        except:
            pydev_log.exception()
    def run(self, file):
        m = save_main_module(file, 'run_profiler')
        globals = m.__dict__
        try:
            globals['__builtins__'] = __builtins__
        except NameError:
            pass  # Not there on Jython...

        self.start_profiling()

        try:
            pydev_imports.execfile(file, globals, globals)  # execute the script
        finally:
            self.stop_profiling()
            self.save_snapshot(0, generate_snapshot_filepath(base_snapshot_path, remote_run, self.snapshot_extension()), remote_run)
Ejemplo n.º 6
0
    def run(self, file):
        m = save_main_module(file, 'run_profiler')
        globals = m.__dict__
        try:
            globals['__builtins__'] = __builtins__
        except NameError:
            pass  # Not there on Jython...

        self.start_profiling()

        try:
            pydev_imports.execfile(file, globals,
                                   globals)  # execute the script
        finally:
            self.stop_profiling()
            self.save_snapshot(
                0, generate_snapshot_filepath(base_snapshot_path, remote_run),
                remote_run)
Ejemplo n.º 7
0
def custom_operation(thread_id, frame_id, scope, attrs, style, code_or_file, operation_fn_name):
    """
    We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var.

    code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed.
    operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint)
    """
    expressionValue = getVariable(thread_id, frame_id, scope, attrs)

    try:
        namespace = {'__name__': '<custom_operation>'}
        if style == "EXECFILE":
            namespace['__file__'] = code_or_file
            execfile(code_or_file, namespace, namespace)
        else:  # style == EXEC
            namespace['__file__'] = '<customOperationCode>'
            Exec(code_or_file, namespace, namespace)

        return str(namespace[operation_fn_name](expressionValue))
    except:
        traceback.print_exc()
Ejemplo n.º 8
0
def custom_operation(thread_id, frame_id, scope, attrs, style, code_or_file, operation_fn_name):
    """
    We'll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var.

    code_or_file: either some code (i.e.: from pprint import pprint) or a file to be executed.
    operation_fn_name: the name of the operation to execute after the exec (i.e.: pprint)
    """
    expressionValue = getVariable(thread_id, frame_id, scope, attrs)

    try:
        namespace = {'__name__': '<custom_operation>'}
        if style == "EXECFILE":
            namespace['__file__'] = code_or_file
            execfile(code_or_file, namespace, namespace)
        else:  # style == EXEC
            namespace['__file__'] = '<customOperationCode>'
            Exec(code_or_file, namespace, namespace)

        return str(namespace[operation_fn_name](expressionValue))
    except:
        traceback.print_exc()
def run_file(file, globals=None, locals=None):
    if os.path.isdir(file):
        new_target = os.path.join(file, "__main__.py")
        if os.path.isfile(new_target):
            file = new_target

    if globals is None:
        m = save_main_module(file, "pydev_run_in_console")

        globals = m.__dict__
        try:
            globals["__builtins__"] = __builtins__
        except NameError:
            pass  # Not there on Jython...

    if locals is None:
        locals = globals

    sys.path.insert(0, os.path.split(file)[0])

    print("Running %s" % file)
    pydev_imports.execfile(file, globals, locals)  # execute the script

    return globals
Ejemplo n.º 10
0
def runfile(filename, args=None, wdir=None, is_module=False, global_vars=None):
    """
    Run filename
    args: command line arguments (string)
    wdir: working directory
    """
    try:
        if hasattr(filename, 'decode'):
            filename = filename.decode('utf-8')
    except (UnicodeError, TypeError):
        pass

    global __umd__
    if os.environ.get("PYDEV_UMD_ENABLED", "").lower() == "true":
        if __umd__ is None:
            namelist = os.environ.get("PYDEV_UMD_NAMELIST", None)
            if namelist is not None:
                namelist = namelist.split(',')
            __umd__ = UserModuleDeleter(namelist=namelist)
        else:
            verbose = os.environ.get("PYDEV_UMD_VERBOSE", "").lower() == "true"
            __umd__.run(verbose=verbose)

    if global_vars is None:
        m = save_main_module(filename, 'pydev_umd')
        global_vars = _get_interpreter_globals()
        global_vars.update(m.__dict__)
        try:
            global_vars['__builtins__'] = __builtins__
        except NameError:
            pass  # Not there on Jython...

    local_vars = global_vars

    module_name = None
    entry_point_fn = None
    if is_module:
        file, _, entry_point_fn = filename.partition(':')
        module_name = file
        filename = get_fullname(file)
        if filename is None:
            sys.stderr.write("No module named %s\n" % file)
            return
    else:
        # The file being run must be in the pythonpath (even if it was not before)
        sys.path.insert(0, os.path.split(rPath(filename))[0])

    global_vars['__file__'] = filename

    sys.argv = [filename]
    if args is not None:
        for arg in args:
            sys.argv.append(arg)

    if wdir is not None:
        try:
            if hasattr(wdir, 'decode'):
                wdir = wdir.decode('utf-8')
        except (UnicodeError, TypeError):
            pass
        os.chdir(wdir)

    try:
        if not is_module:
            pydev_imports.execfile(filename, global_vars,
                                   local_vars)  # execute the script
        else:
            # treat ':' as a seperator between module and entry point function
            # if there is no entry point we run we same as with -m switch. Otherwise we perform
            # an import and execute the entry point
            if entry_point_fn:
                mod = __import__(module_name,
                                 level=0,
                                 fromlist=[entry_point_fn],
                                 globals=global_vars,
                                 locals=local_vars)
                func = getattr(mod, entry_point_fn)
                func()
            else:
                # Run with the -m switch
                import runpy
                if hasattr(runpy, '_run_module_as_main'):
                    runpy._run_module_as_main(module_name)
                else:
                    runpy.run_module(module_name)
    finally:
        sys.argv = ['']
        interpreter_globals = _get_interpreter_globals()
        interpreter_globals.update(global_vars)
Ejemplo n.º 11
0
def runfile(filename, args=None, wdir=None, is_module=False, global_vars=None):
    """
    Run filename
    args: command line arguments (string)
    wdir: working directory
    """
    try:
        if hasattr(filename, 'decode'):
            filename = filename.decode('utf-8')
    except (UnicodeError, TypeError):
        pass

    global __umd__
    if os.environ.get("PYDEV_UMD_ENABLED", "").lower() == "true":
        if __umd__ is None:
            namelist = os.environ.get("PYDEV_UMD_NAMELIST", None)
            if namelist is not None:
                namelist = namelist.split(',')
            __umd__ = UserModuleDeleter(namelist=namelist)
        else:
            verbose = os.environ.get("PYDEV_UMD_VERBOSE", "").lower() == "true"
            __umd__.run(verbose=verbose)

    if global_vars is None:
        m = save_main_module(filename, 'pydev_umd')
        global_vars = m.__dict__
        try:
            global_vars['__builtins__'] = __builtins__
        except NameError:
            pass  # Not there on Jython...

    local_vars = global_vars

    module_name = None
    entry_point_fn = None
    if is_module:
        file, _, entry_point_fn = filename.partition(':')
        module_name = file
        filename = get_fullname(file)
        if filename is None:
            sys.stderr.write("No module named %s\n" % file)
            return
    else:
        # The file being run must be in the pythonpath (even if it was not before)
        sys.path.insert(0, os.path.split(rPath(filename))[0])

    global_vars['__file__'] = filename

    sys.argv = [filename]
    if args is not None:
        for arg in args:
            sys.argv.append(arg)

    if wdir is not None:
        try:
            if hasattr(wdir, 'decode'):
                wdir = wdir.decode('utf-8')
        except (UnicodeError, TypeError):
            pass
        os.chdir(wdir)

    try:
        if not is_module:
            pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
        else:
            # treat ':' as a seperator between module and entry point function
            # if there is no entry point we run we same as with -m switch. Otherwise we perform
            # an import and execute the entry point
            if entry_point_fn:
                mod = __import__(module_name, level=0, fromlist=[entry_point_fn], globals=global_vars, locals=local_vars)
                func = getattr(mod, entry_point_fn)
                func()
            else:
                # Run with the -m switch
                import runpy
                if hasattr(runpy, '_run_module_as_main'):
                    runpy._run_module_as_main(module_name)
                else:
                    runpy.run_module(module_name)
    finally:
        sys.argv = ['']
        interpreter_globals = _get_interpreter_globals()
        interpreter_globals.update(global_vars)