Python runpy.run_module() Examples

The following are 30 code examples of runpy.run_module(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module runpy , or try the search function .
Example #1
Source File: test_training.py    From vecto with Mozilla Public License 2.0 8 votes vote down vote up
def test_train_word2vec_subword_jap(self):
        path_corpus = "./tests/data/corpora/jap/tokenized/"
        path_word2chars = "./tests/data/corpora/jap/char2radical/char2radical.txt"
        sio = io.StringIO()
        with contextlib.redirect_stderr(sio):
            run_module('vecto.embeddings.train_word2vec',
                       ['--path_corpus', path_corpus, '--path_out', '/tmp/vecto/embeddings/', '--dimension', '5',
                        '--subword', 'sum', '--language', 'jap', '--min_gram', '1', '--max_gram', '1'])
            run_module('vecto.embeddings.train_word2vec',
                       ['--path_corpus', path_corpus, '--path_out', '/tmp/vecto/embeddings/', '--dimension', '5',
                        '--subword', 'sum', '--language', 'jap', '--min_gram', '1', '--max_gram', '1',
                        '--path_word2chars', path_word2chars])

            with self.assertRaises(RuntimeError):
                run_module('vecto.embeddings.train_word2vec',
                           ['--path_corpus', path_corpus + "NONEXISTING", '--path_out', '/tmp/vecto/embeddings/',
                            '--dimension', '5',
                            '--subword', 'sum', '--language', 'jap', '--min_gram', '1', '--max_gram', '1']) 
Example #2
Source File: auto2to3.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 7 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--package', action='append')
    parser.add_argument('--dir', action='append')
    parser.add_argument('-m', action='store', metavar='MODULE')
    args, rest = parser.parse_known_args()
    if args.package:
        PACKAGES.extend(args.package)
    if args.dir:
        DIRS.extend(os.path.abspath(d) for d in args.dir)
    if not PACKAGES and not DIRS:
        DIRS.append(os.getcwd())
    if args.m:
        sys.argv[1:] = rest
        runpy.run_module(args.m, run_name='__main__', alter_sys=True)
    elif rest:
        sys.argv = rest
        converted = maybe_2to3(rest[0])
        with open(converted) as f:
            new_globals = dict(__name__='__main__',
                               __file__=rest[0])
            exec(f.read(), new_globals)
    else:
        import code
        code.interact() 
Example #3
Source File: spawn.py    From Imogen with MIT License 6 votes vote down vote up
def _fixup_main_from_name(mod_name):
    # __main__.py files for packages, directories, zip archives, etc, run
    # their "main only" code unconditionally, so we don't even try to
    # populate anything in __main__, nor do we make any changes to
    # __main__ attributes
    current_main = sys.modules['__main__']
    if mod_name == "__main__" or mod_name.endswith(".__main__"):
        return

    # If this process was forked, __main__ may already be populated
    if getattr(current_main.__spec__, "name", None) == mod_name:
        return

    # Otherwise, __main__ may contain some non-main code where we need to
    # support unpickling it properly. We rerun it as __mp_main__ and make
    # the normal __main__ an alias to that
    old_main_modules.append(current_main)
    main_module = types.ModuleType("__mp_main__")
    main_content = runpy.run_module(mod_name,
                                    run_name="__mp_main__",
                                    alter_sys=True)
    main_module.__dict__.update(main_content)
    sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module 
Example #4
Source File: interactiveshell.py    From Computable with MIT License 6 votes vote down vote up
def safe_run_module(self, mod_name, where):
        """A safe version of runpy.run_module().

        This version will never throw an exception, but instead print
        helpful error messages to the screen.

        `SystemExit` exceptions with status code 0 or None are ignored.

        Parameters
        ----------
        mod_name : string
            The name of the module to be executed.
        where : dict
            The globals namespace.
        """
        try:
            try:
                where.update(
                    runpy.run_module(str(mod_name), run_name="__main__",
                                     alter_sys=True)
                    )
            except SystemExit as status:
                if status.code:
                    raise
        except:
            self.showtraceback()
            warn('Unknown failure executing module: <%s>' % mod_name) 
Example #5
Source File: test_runpy.py    From BinderFilter with MIT License 6 votes vote down vote up
def _check_package(self, depth):
        pkg_dir, mod_fname, mod_name = (
               self._make_pkg("x=1\n", depth, "__main__"))
        pkg_name, _, _ = mod_name.rpartition(".")
        forget(mod_name)
        try:
            if verbose: print "Running from source:", pkg_name
            d1 = run_module(pkg_name) # Read from source
            self.assertIn("x", d1)
            self.assertTrue(d1["x"] == 1)
            del d1 # Ensure __loader__ entry doesn't keep file open
            __import__(mod_name)
            os.remove(mod_fname)
            if not sys.dont_write_bytecode:
                if verbose: print "Running from compiled:", pkg_name
                d2 = run_module(pkg_name) # Read from bytecode
                self.assertIn("x", d2)
                self.assertTrue(d2["x"] == 1)
                del d2 # Ensure __loader__ entry doesn't keep file open
        finally:
            self._del_pkg(pkg_dir, depth, pkg_name)
        if verbose: print "Package executed successfully" 
Example #6
Source File: test_runpy.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_run_name(self):
        depth = 1
        run_name = "And now for something completely different"
        pkg_dir, mod_fname, mod_name, mod_spec = (
               self._make_pkg(example_source, depth))
        forget(mod_name)
        expected_ns = example_namespace.copy()
        expected_ns.update({
            "__name__": run_name,
            "__file__": mod_fname,
            "__cached__": importlib.util.cache_from_source(mod_fname),
            "__package__": mod_name.rpartition(".")[0],
            "__spec__": mod_spec,
        })
        def create_ns(init_globals):
            return run_module(mod_name, init_globals, run_name)
        try:
            self.check_code_execution(create_ns, expected_ns)
        finally:
            self._del_pkg(pkg_dir) 
Example #7
Source File: test_runpy.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _check_module(self, depth):
        pkg_dir, mod_fname, mod_name = (
               self._make_pkg("x=1\n", depth))
        forget(mod_name)
        try:
            if verbose: print "Running from source:", mod_name
            d1 = run_module(mod_name) # Read from source
            self.assertIn("x", d1)
            self.assertTrue(d1["x"] == 1)
            del d1 # Ensure __loader__ entry doesn't keep file open
            __import__(mod_name)
            os.remove(mod_fname)
            if not sys.dont_write_bytecode:
                if verbose: print "Running from compiled:", mod_name
                d2 = run_module(mod_name) # Read from bytecode
                self.assertIn("x", d2)
                self.assertTrue(d2["x"] == 1)
                del d2 # Ensure __loader__ entry doesn't keep file open
        finally:
            self._del_pkg(pkg_dir, depth, mod_name)
        if verbose: print "Module executed successfully" 
Example #8
Source File: test_runpy.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _check_package(self, depth):
        pkg_dir, mod_fname, mod_name = (
               self._make_pkg("x=1\n", depth, "__main__"))
        pkg_name, _, _ = mod_name.rpartition(".")
        forget(mod_name)
        try:
            if verbose: print "Running from source:", pkg_name
            d1 = run_module(pkg_name) # Read from source
            self.assertIn("x", d1)
            self.assertTrue(d1["x"] == 1)
            del d1 # Ensure __loader__ entry doesn't keep file open
            __import__(mod_name)
            os.remove(mod_fname)
            if not sys.dont_write_bytecode:
                if verbose: print "Running from compiled:", pkg_name
                d2 = run_module(pkg_name) # Read from bytecode
                self.assertIn("x", d2)
                self.assertTrue(d2["x"] == 1)
                del d2 # Ensure __loader__ entry doesn't keep file open
        finally:
            self._del_pkg(pkg_dir, depth, pkg_name)
        if verbose: print "Package executed successfully" 
Example #9
Source File: test_runpy.py    From BinderFilter with MIT License 6 votes vote down vote up
def _check_module(self, depth):
        pkg_dir, mod_fname, mod_name = (
               self._make_pkg("x=1\n", depth))
        forget(mod_name)
        try:
            if verbose: print "Running from source:", mod_name
            d1 = run_module(mod_name) # Read from source
            self.assertIn("x", d1)
            self.assertTrue(d1["x"] == 1)
            del d1 # Ensure __loader__ entry doesn't keep file open
            __import__(mod_name)
            os.remove(mod_fname)
            if not sys.dont_write_bytecode:
                if verbose: print "Running from compiled:", mod_name
                d2 = run_module(mod_name) # Read from bytecode
                self.assertIn("x", d2)
                self.assertTrue(d2["x"] == 1)
                del d2 # Ensure __loader__ entry doesn't keep file open
        finally:
            self._del_pkg(pkg_dir, depth, mod_name)
        if verbose: print "Module executed successfully" 
Example #10
Source File: test_runpy.py    From oss-ftp with MIT License 6 votes vote down vote up
def _check_module(self, depth):
        pkg_dir, mod_fname, mod_name = (
               self._make_pkg("x=1\n", depth))
        forget(mod_name)
        try:
            if verbose: print "Running from source:", mod_name
            d1 = run_module(mod_name) # Read from source
            self.assertIn("x", d1)
            self.assertTrue(d1["x"] == 1)
            del d1 # Ensure __loader__ entry doesn't keep file open
            __import__(mod_name)
            os.remove(mod_fname)
            if not sys.dont_write_bytecode:
                if verbose: print "Running from compiled:", mod_name
                d2 = run_module(mod_name) # Read from bytecode
                self.assertIn("x", d2)
                self.assertTrue(d2["x"] == 1)
                del d2 # Ensure __loader__ entry doesn't keep file open
        finally:
            self._del_pkg(pkg_dir, depth, mod_name)
        if verbose: print "Module executed successfully" 
Example #11
Source File: test_runpy.py    From oss-ftp with MIT License 6 votes vote down vote up
def _check_package(self, depth):
        pkg_dir, mod_fname, mod_name = (
               self._make_pkg("x=1\n", depth, "__main__"))
        pkg_name, _, _ = mod_name.rpartition(".")
        forget(mod_name)
        try:
            if verbose: print "Running from source:", pkg_name
            d1 = run_module(pkg_name) # Read from source
            self.assertIn("x", d1)
            self.assertTrue(d1["x"] == 1)
            del d1 # Ensure __loader__ entry doesn't keep file open
            __import__(mod_name)
            os.remove(mod_fname)
            if not sys.dont_write_bytecode:
                if verbose: print "Running from compiled:", pkg_name
                d2 = run_module(pkg_name) # Read from bytecode
                self.assertIn("x", d2)
                self.assertTrue(d2["x"] == 1)
                del d2 # Ensure __loader__ entry doesn't keep file open
        finally:
            self._del_pkg(pkg_dir, depth, pkg_name)
        if verbose: print "Package executed successfully" 
Example #12
Source File: script.py    From flambe with MIT License 6 votes vote down vote up
def run(self) -> bool:
        """Run the evaluation.

        Returns
        -------
        Dict[str, float]
            Report dictionary to use for logging

        """
        parser_kwargs = {f'--{k}': v for k, v in self.kwargs.items()}
        # Flatten the arguments into a single list to pass to sys.argv
        parser_args_flat = [str(item) for item in self.args]
        parser_args_flat += [str(item) for items in parser_kwargs.items() for item in items]

        sys_save = deepcopy(sys.argv)
        sys.argv = [''] + parser_args_flat  # add dummy sys[0]
        runpy.run_module(self.script, run_name='__main__', alter_sys=True)
        sys.argv = sys_save

        continue_ = False  # Single step, so don't continue
        return continue_ 
Example #13
Source File: yaml_lint.py    From runway with Apache License 2.0 6 votes vote down vote up
def handle(cls, name, args):
        # type: (str, Dict[str, Any]) -> None
        """Perform the actual test."""
        base_dir = os.getcwd()

        if os.path.isfile(os.path.join(base_dir, '.yamllint')):
            yamllint_config = os.path.join(base_dir, '.yamllint')
        elif os.path.isfile(os.path.join(base_dir, '.yamllint.yml')):
            yamllint_config = os.path.join(base_dir, '.yamllint.yml')
        else:
            yamllint_config = os.path.join(
                os.path.dirname(os.path.dirname(os.path.dirname(
                    os.path.abspath(__file__)
                ))),
                'templates',
                '.yamllint.yml'
            )

        yamllint_options = ["--config-file=%s" % yamllint_config]
        yamllint_options.extend(cls.get_yamllint_options(base_dir))

        with argv(*['yamllint'] + yamllint_options):
            runpy.run_module('yamllint', run_name='__main__') 
Example #14
Source File: cfn_lint.py    From runway with Apache License 2.0 6 votes vote down vote up
def handle(cls, name, args):
        # type: (str, Dict[str, Any]) -> None
        """Perform the actual test.

        Relies on .cfnlintrc file to be located beside the Runway config file.

        """
        cfnlintrc = Path('./.cfnlintrc')

        if not cfnlintrc.is_file():
            LOGGER.error('File must exist to use this test: %s', cfnlintrc)
            sys.exit(1)

        # prevent duplicate log messages by not passing to the root logger
        logging.getLogger('cfnlint').propagate = False
        try:
            with argv(*['cfn-lint'] + args.get('cli_args', [])):
                runpy.run_module('cfnlint', run_name='__main__')
        except SystemExit as err:  # this call will always result in SystemExit
            if err.code != 0:  # ignore zero exit codes but re-raise for non-zero
                if not (yaml.safe_load(cfnlintrc.read_text()) or
                        {}).get('templates'):
                    LOGGER.warning('cfnlintrc is missing a "templates" '
                                   'section which is required by cfn-lint')
                raise 
Example #15
Source File: test_runpy.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _check_package(self, depth):
        pkg_dir, mod_fname, mod_name = (
               self._make_pkg("x=1\n", depth, "__main__"))
        pkg_name, _, _ = mod_name.rpartition(".")
        forget(mod_name)
        try:
            if verbose: print "Running from source:", pkg_name
            d1 = run_module(pkg_name) # Read from source
            self.assertIn("x", d1)
            self.assertTrue(d1["x"] == 1)
            del d1 # Ensure __loader__ entry doesn't keep file open
            __import__(mod_name)
            os.remove(mod_fname)
            if not sys.dont_write_bytecode:
                if verbose: print "Running from compiled:", pkg_name
                d2 = run_module(pkg_name) # Read from bytecode
                self.assertIn("x", d2)
                self.assertTrue(d2["x"] == 1)
                del d2 # Ensure __loader__ entry doesn't keep file open
        finally:
            self._del_pkg(pkg_dir, depth, pkg_name)
        if verbose: print "Package executed successfully" 
Example #16
Source File: test_runpy.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _check_module(self, depth):
        pkg_dir, mod_fname, mod_name = (
               self._make_pkg("x=1\n", depth))
        forget(mod_name)
        try:
            if verbose: print "Running from source:", mod_name
            d1 = run_module(mod_name) # Read from source
            self.assertIn("x", d1)
            self.assertTrue(d1["x"] == 1)
            del d1 # Ensure __loader__ entry doesn't keep file open
            __import__(mod_name)
            os.remove(mod_fname)
            if not sys.dont_write_bytecode:
                if verbose: print "Running from compiled:", mod_name
                d2 = run_module(mod_name) # Read from bytecode
                self.assertIn("x", d2)
                self.assertTrue(d2["x"] == 1)
                del d2 # Ensure __loader__ entry doesn't keep file open
        finally:
            self._del_pkg(pkg_dir, depth, mod_name)
        if verbose: print "Module executed successfully" 
Example #17
Source File: runner.py    From kitty with GNU General Public License v3.0 6 votes vote down vote up
def run_kitten(kitten: str, run_name: str = '__main__') -> None:
    import runpy
    original_kitten_name = kitten
    kitten = resolved_kitten(kitten)
    set_debug(kitten)
    try:
        runpy.run_module('kittens.{}.main'.format(kitten), run_name=run_name)
        return
    except ImportError:
        pass
    # Look for a custom kitten
    if not kitten.endswith('.py'):
        kitten += '.py'
    from kitty.constants import config_dir
    path = path_to_custom_kitten(config_dir, kitten)
    if not os.path.exists(path):
        print('Available builtin kittens:', file=sys.stderr)
        for kitten in all_kitten_names():
            print(kitten, file=sys.stderr)
        raise SystemExit('No kitten named {}'.format(original_kitten_name))
    m = runpy.run_path(path, init_globals={'sys': sys, 'os': os}, run_name='__run_kitten__')
    m['main'](sys.argv) 
Example #18
Source File: spawn.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def _fixup_main_from_name(mod_name):
    # __main__.py files for packages, directories, zip archives, etc, run
    # their "main only" code unconditionally, so we don't even try to
    # populate anything in __main__, nor do we make any changes to
    # __main__ attributes
    current_main = sys.modules['__main__']
    if mod_name == "__main__" or mod_name.endswith(".__main__"):
        return

    # If this process was forked, __main__ may already be populated
    if getattr(current_main.__spec__, "name", None) == mod_name:
        return

    # Otherwise, __main__ may contain some non-main code where we need to
    # support unpickling it properly. We rerun it as __mp_main__ and make
    # the normal __main__ an alias to that
    old_main_modules.append(current_main)
    main_module = types.ModuleType("__mp_main__")
    main_content = runpy.run_module(mod_name,
                                    run_name="__mp_main__",
                                    alter_sys=True)
    main_module.__dict__.update(main_content)
    sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module 
Example #19
Source File: spawn.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _fixup_main_from_name(mod_name):
    # __main__.py files for packages, directories, zip archives, etc, run
    # their "main only" code unconditionally, so we don't even try to
    # populate anything in __main__, nor do we make any changes to
    # __main__ attributes
    current_main = sys.modules['__main__']
    if mod_name == "__main__" or mod_name.endswith(".__main__"):
        return

    # If this process was forked, __main__ may already be populated
    if getattr(current_main.__spec__, "name", None) == mod_name:
        return

    # Otherwise, __main__ may contain some non-main code where we need to
    # support unpickling it properly. We rerun it as __mp_main__ and make
    # the normal __main__ an alias to that
    old_main_modules.append(current_main)
    main_module = types.ModuleType("__mp_main__")
    main_content = runpy.run_module(mod_name,
                                    run_name="__mp_main__",
                                    alter_sys=True)
    main_module.__dict__.update(main_content)
    sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module 
Example #20
Source File: spawn.py    From loky with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _fixup_main_from_name(mod_name):
    # __main__.py files for packages, directories, zip archives, etc, run
    # their "main only" code unconditionally, so we don't even try to
    # populate anything in __main__, nor do we make any changes to
    # __main__ attributes
    current_main = sys.modules['__main__']
    if mod_name == "__main__" or mod_name.endswith(".__main__"):
        return

    # If this process was forked, __main__ may already be populated
    if getattr(current_main.__spec__, "name", None) == mod_name:
        return

    # Otherwise, __main__ may contain some non-main code where we need to
    # support unpickling it properly. We rerun it as __mp_main__ and make
    # the normal __main__ an alias to that
    old_main_modules.append(current_main)
    main_module = types.ModuleType("__mp_main__")
    main_content = runpy.run_module(mod_name,
                                    run_name="__mp_main__",
                                    alter_sys=True)
    main_module.__dict__.update(main_content)
    sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module 
Example #21
Source File: spawn.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def _fixup_main_from_name(mod_name):
    # __main__.py files for packages, directories, zip archives, etc, run
    # their "main only" code unconditionally, so we don't even try to
    # populate anything in __main__, nor do we make any changes to
    # __main__ attributes
    current_main = sys.modules['__main__']
    if mod_name == "__main__" or mod_name.endswith(".__main__"):
        return

    # If this process was forked, __main__ may already be populated
    if getattr(current_main.__spec__, "name", None) == mod_name:
        return

    # Otherwise, __main__ may contain some non-main code where we need to
    # support unpickling it properly. We rerun it as __mp_main__ and make
    # the normal __main__ an alias to that
    old_main_modules.append(current_main)
    main_module = types.ModuleType("__mp_main__")
    main_content = runpy.run_module(mod_name,
                                    run_name="__mp_main__",
                                    alter_sys=True)
    main_module.__dict__.update(main_content)
    sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module 
Example #22
Source File: test_runpy.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _check_module(self, depth, alter_sys=False,
                         *, namespace=False, parent_namespaces=False):
        pkg_dir, mod_fname, mod_name, mod_spec = (
               self._make_pkg(example_source, depth,
                              namespace=namespace,
                              parent_namespaces=parent_namespaces))
        forget(mod_name)
        expected_ns = example_namespace.copy()
        expected_ns.update({
            "__name__": mod_name,
            "__file__": mod_fname,
            "__cached__": mod_spec.cached,
            "__package__": mod_name.rpartition(".")[0],
            "__spec__": mod_spec,
        })
        if alter_sys:
            expected_ns.update({
                "run_argv0": mod_fname,
                "run_name_in_sys_modules": True,
                "module_in_sys_modules": True,
            })
        def create_ns(init_globals):
            return run_module(mod_name, init_globals, alter_sys=alter_sys)
        try:
            if verbose > 1: print("Running from source:", mod_name)
            self.check_code_execution(create_ns, expected_ns)
            importlib.invalidate_caches()
            __import__(mod_name)
            os.remove(mod_fname)
            if not sys.dont_write_bytecode:
                make_legacy_pyc(mod_fname)
                unload(mod_name)  # In case loader caches paths
                importlib.invalidate_caches()
                if verbose > 1: print("Running from compiled:", mod_name)
                self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
                self.check_code_execution(create_ns, expected_ns)
        finally:
            self._del_pkg(pkg_dir, depth, mod_name)
        if verbose > 1: print("Module executed successfully") 
Example #23
Source File: test_runpy.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def expect_import_error(self, mod_name):
        try:
            run_module(mod_name)
        except ImportError:
            pass
        else:
            self.fail("Expected import error for " + mod_name) 
Example #24
Source File: test_runpy.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def expect_import_error(self, mod_name):
        try:
            run_module(mod_name)
        except ImportError:
            pass
        else:
            self.fail("Expected import error for " + mod_name) 
Example #25
Source File: visualstudio_py_util.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def exec_module(module, global_variables):
    '''Executes the provided module as if it were provided as '-m module'. The
    functionality is implemented using `runpy.run_module`, which was added in
    Python 2.5.
    '''
    import runpy
    runpy.run_module(module, global_variables, run_name=global_variables.get('__name__'), alter_sys=True) 
Example #26
Source File: test_runpy.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _check_package(self, depth, alter_sys=False,
                          *, namespace=False, parent_namespaces=False):
        pkg_dir, mod_fname, mod_name, mod_spec = (
               self._make_pkg(example_source, depth, "__main__",
                              namespace=namespace,
                              parent_namespaces=parent_namespaces))
        pkg_name = mod_name.rpartition(".")[0]
        forget(mod_name)
        expected_ns = example_namespace.copy()
        expected_ns.update({
            "__name__": mod_name,
            "__file__": mod_fname,
            "__cached__": importlib.util.cache_from_source(mod_fname),
            "__package__": pkg_name,
            "__spec__": mod_spec,
        })
        if alter_sys:
            expected_ns.update({
                "run_argv0": mod_fname,
                "run_name_in_sys_modules": True,
                "module_in_sys_modules": True,
            })
        def create_ns(init_globals):
            return run_module(pkg_name, init_globals, alter_sys=alter_sys)
        try:
            if verbose > 1: print("Running from source:", pkg_name)
            self.check_code_execution(create_ns, expected_ns)
            importlib.invalidate_caches()
            __import__(mod_name)
            os.remove(mod_fname)
            if not sys.dont_write_bytecode:
                make_legacy_pyc(mod_fname)
                unload(mod_name)  # In case loader caches paths
                if verbose > 1: print("Running from compiled:", pkg_name)
                importlib.invalidate_caches()
                self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
                self.check_code_execution(create_ns, expected_ns)
        finally:
            self._del_pkg(pkg_dir, depth, pkg_name)
        if verbose > 1: print("Package executed successfully") 
Example #27
Source File: test_runpy.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _check_relative_imports(self, depth, run_name=None):
        contents = r"""\
from __future__ import absolute_import
from . import sibling
from ..uncle.cousin import nephew
"""
        pkg_dir, mod_fname, mod_name, mod_spec = (
               self._make_pkg(contents, depth))
        if run_name is None:
            expected_name = mod_name
        else:
            expected_name = run_name
        try:
            self._add_relative_modules(pkg_dir, contents, depth)
            pkg_name = mod_name.rpartition('.')[0]
            if verbose > 1: print("Running from source:", mod_name)
            d1 = run_module(mod_name, run_name=run_name) # Read from source
            self.assertEqual(d1["__name__"], expected_name)
            self.assertEqual(d1["__package__"], pkg_name)
            self.assertIn("sibling", d1)
            self.assertIn("nephew", d1)
            del d1 # Ensure __loader__ entry doesn't keep file open
            importlib.invalidate_caches()
            __import__(mod_name)
            os.remove(mod_fname)
            if not sys.dont_write_bytecode:
                make_legacy_pyc(mod_fname)
                unload(mod_name)  # In case the loader caches paths
                if verbose > 1: print("Running from compiled:", mod_name)
                importlib.invalidate_caches()
                d2 = run_module(mod_name, run_name=run_name) # Read from bytecode
                self.assertEqual(d2["__name__"], expected_name)
                self.assertEqual(d2["__package__"], pkg_name)
                self.assertIn("sibling", d2)
                self.assertIn("nephew", d2)
                del d2 # Ensure __loader__ entry doesn't keep file open
        finally:
            self._del_pkg(pkg_dir, depth, mod_name)
        if verbose > 1: print("Module executed successfully") 
Example #28
Source File: visualstudio_py_util.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def exec_module(module, global_variables):
    '''Executes the provided module as if it were provided as '-m module'. The
    functionality is implemented using `runpy.run_module`, which was added in
    Python 2.5.
    '''
    import runpy
    runpy.run_module(module, global_variables, run_name=global_variables.get('__name__'), alter_sys=True) 
Example #29
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def execute_module_work_item(self):
        new_argv = [''] + _command_line_to_args_list(self.current_args)
        old_argv = sys.argv
        import runpy
        try:
            sys.argv = new_argv
            runpy.run_module(self.current_code, alter_sys=True)
        except Exception:
            traceback.print_exc()
        finally:
            sys.argv = old_argv 
Example #30
Source File: test_runpy.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_library_module(self):
        self.assertEqual(run_module("runpy")["__name__"], "runpy")