def exec_module(loader, module=None, **globals): import runpy module = module or loader.create_module() vars(module).update(globals) runpy._run_code(loader.main_code, vars(module), {}, '__main__', module.__spec__, None, None) return module
def create_module(loader, spec=None): import runpy if spec is None: import importlib spec = importlib.util.spec_from_loader(loader.name, loader) module = super(type(loader), loader).create_module(spec) loader.main_code = loader.get_code(loader.name) runpy._run_code(loader.arg_code, vars(module), {}, '__main__', spec, None, None) return module
def _run_module_code(code, init_globals=None, mod_name=None, mod_spec=None, pkg_name=None, script_name=None): """Helper to run code in new namespace with sys modified""" fname = script_name if mod_spec is None else mod_spec.origin with _TempModule(mod_name) as temp_module, _ModifiedArgv0(fname): mod_globals = temp_module.module.__dict__ try: _run_code(code, mod_globals, init_globals, mod_name, mod_spec, pkg_name, script_name) except Exception as error: mod_globals['__run_module_error__'] = error # Copy the globals of the temporary module, as they # may be cleared when the temporary module goes away return mod_globals.copy()
def test_run_code(self): saved_argv0 = sys.argv[0] d = _run_code(self.test_source, {}) self.assertEqual(d["result"], self.expected_result) self.assertIs(d["__name__"], None) self.assertIs(d["__file__"], None) self.assertIs(d["__loader__"], None) self.assertIs(d["__package__"], None) self.assertIs(d["run_argv0"], saved_argv0) self.assertNotIn("run_name", d) self.assertIs(sys.argv[0], saved_argv0)
def test_run_code(self): saved_argv0 = sys.argv[0] d = _run_code(self.test_source, {}) self.assertTrue(d["result"] == self.expected_result) self.assertTrue(d["__name__"] is None) self.assertTrue(d["__file__"] is None) self.assertTrue(d["__loader__"] is None) self.assertTrue(d["__package__"] is None) self.assertTrue(d["run_argv0"] is saved_argv0) self.assertTrue("run_name" not in d) self.assertTrue(sys.argv[0] is saved_argv0)
def test_run_code(self): saved_argv0 = sys.argv[0] d = _run_code(self.test_source, {}) self.failUnless(d["result"] == self.expected_result) self.failUnless(d["__name__"] is None) self.failUnless(d["__file__"] is None) self.failUnless(d["__loader__"] is None) self.failUnless(d["__package__"] is None) self.failUnless(d["run_argv0"] is saved_argv0) self.failUnless("run_name" not in d) self.failUnless(sys.argv[0] is saved_argv0)
def create_ns(init_globals): return _run_code(example_source, {}, init_globals)
def load(self, clear=False): """ Loads all the config plugin modules to build a working configuration. If there is a ``localconfig`` module on the python path, it will be loaded last, overriding other settings. :param bool clear: Clear out the previous settings before loading """ if clear: self.settings = {} defer = [] # Load all config plugins for conf in pkg_resources.iter_entry_points('pyconfig'): if conf.attrs: raise RuntimeError("config must be a module") mod_name = conf.module_name base_name = conf.name if conf.name != 'any' else None log.info("Loading module '%s'", mod_name) mod_dict = runpy.run_module(mod_name) # If this module wants to be deferred, save it for later if mod_dict.get('deferred', None) is deferred: log.info("Deferring module '%s'", mod_name) mod_dict.pop('deferred') defer.append((mod_name, base_name, mod_dict)) continue self._update(mod_dict, base_name) # Load deferred modules for mod_name, base_name, mod_dict in defer: log.info("Loading deferred module '%s'", mod_name) self._update(mod_dict, base_name) if etcd().configured: # Load etcd stuff mod_dict = etcd().load() if mod_dict: self._update(mod_dict) # Allow localconfig overrides mod_dict = None try: mod_dict = runpy.run_module('localconfig') except ImportError: pass except ValueError as err: if getattr(err, 'message') != '__package__ set to non-string': raise # This is a bad work-around to make this work transparently... # shouldn't really access core stuff like this, but F**k It[tm] mod_name = 'localconfig' if sys.version_info < (2, 7): loader, code, fname = runpy._get_module_details(mod_name) else: _, loader, code, fname = runpy._get_module_details(mod_name) mod_dict = runpy._run_code(code, {}, {}, mod_name, fname, loader, pkg_name=None) if mod_dict: log.info("Loading module 'localconfig'") self._update(mod_dict) self.call_reload_hooks()
def load(self, clear=False): """ Loads all the config plugin modules to build a working configuration. If there is a ``localconfig`` module on the python path, it will be loaded last, overriding other settings. :param bool clear: Clear out the previous settings before loading """ if clear: self.settings = {} defer = [] # Load all config plugins for conf in pkg_resources.iter_entry_points('pyconfig'): if conf.attrs: raise RuntimeError("config must be a module") mod_name = conf.module_name base_name = conf.name if conf.name != 'any' else None log.info("Loading module '%s'", mod_name) mod_dict = runpy.run_module(mod_name) # If this module wants to be deferred, save it for later if mod_dict.get('deferred', None) is deferred: log.info("Deferring module '%s'", mod_name) mod_dict.pop('deferred') defer.append((mod_name, base_name, mod_dict)) continue self._update(mod_dict, base_name) # Load deferred modules for mod_name, base_name, mod_dict in defer: log.info("Loading deferred module '%s'", mod_name) self._update(mod_dict, base_name) # Allow localconfig overrides mod_dict = None try: mod_dict = runpy.run_module('localconfig') except ImportError: pass except ValueError as err: if getattr(err, 'message') != '__package__ set to non-string': raise # This is a bad work-around to make this work transparently... # shouldn't really access core stuff like this, but F**k It[tm] mod_name = 'localconfig' if sys.version_info < (2, 7): loader, code, fname = runpy._get_module_details(mod_name) else: _, loader, code, fname = runpy._get_module_details(mod_name) mod_dict = runpy._run_code(code, {}, {}, mod_name, fname, loader, pkg_name=None) if mod_dict: log.info("Loading module 'localconfig'") self._update(mod_dict) self.call_reload_hooks()
async def run_remote_async(url: str): with aiohttp.ClientSession(loop=loop) as session: code = await fetch(session, url) res = runpy._run_code(code, run_globals=globals()) return res
# def hello_world(a=dict, b=dict, c=dict, d=dict): # print(a, b, c, d) # # a = hello_world # args = {"a": 3, "b": 8, "c": 12, "d": 1} # print(a.__call__(**args)) import runpy d = {} runpy._run_code(""" """, d, d) def exclusion_generator(base_dict, to_excludes): for item in base_dict.copy().keys(): if item in to_excludes: del base_dict[item] e = {} file = open("items.py", "r") runpy._run_code(file.read(), e, e) exclusion_generator(e, d.keys()) # print(list(e.items())) f = [] for i in tuple(e.items()):
def run_path(path): namespace = {} with open(path) as f: text = f.read() _run_code(text, namespace) return namespace
def exec_code(code: str): runpy._run_code(code, run_globals=globals())
def update_event(self, inp=-1): self.set_output_val(0, runpy._run_code(self.input(0), self.input(1), self.input(2), self.input(3), self.input(4), self.input(5), self.input(6)))