Python runpy.run_path() Examples
The following are 30
code examples of runpy.run_path().
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: flame_graph.py From vprof with BSD 2-Clause "Simplified" License | 7 votes |
def _profile_package(self): """Runs statistical profiler on a package.""" with _StatProfiler() as prof: prof.base_frame = inspect.currentframe() try: runpy.run_path(self._run_object, run_name='__main__') except SystemExit: pass call_tree = prof.call_tree return { 'objectName': self._object_name, 'sampleInterval': _SAMPLE_INTERVAL, 'runTime': prof.run_time, 'callStats': call_tree, 'totalSamples': call_tree.get('sampleCount', 0), 'timestamp': int(time.time()) }
Example #2
Source File: pundle.py From pundler with BSD 2-Clause "Simplified" License | 7 votes |
def get_info_from_setup(path): """Mock setuptools.setup(**kargs) to get package information about requirements and extras """ preserve = {} def _save_info(**setup_args): preserve['args'] = setup_args import setuptools original_setup = setuptools.setup setuptools.setup = _save_info import runpy runpy.run_path(os.path.join(path, 'setup.py'), run_name='__main__') setuptools.setup = original_setup return preserve.get('args')
Example #3
Source File: __init__.py From permon with MIT License | 6 votes |
def _import_all_stats(): """ Import all stats (prepackaged ones and user defined ones). This must only ever be called once. Otherwise they are imported multiple times. """ here = os.path.dirname(os.path.realpath(__file__)) default_stat_dir = os.path.join(here, 'stats', '*.py') custom_stat_dir = os.path.join(config.config_dir, 'stats', '*.permon.py') default_stat_files = glob.glob(default_stat_dir) custom_stat_files = glob.glob(custom_stat_dir) dup = set(os.path.basename(x) for x in default_stat_files).intersection( set(os.path.basename(x) for x in custom_stat_files)) assert len(dup) == 0, \ ('Custom stat files must not have the same name as default ones. ' f'{dup} collides.') for path in default_stat_files + custom_stat_files: runpy.run_path(path, run_name=path)
Example #4
Source File: test_tools.py From ironpython2 with Apache License 2.0 | 6 votes |
def run_script(self, input="", args=("-",), substfile="xx yy\n"): substfilename = test_support.TESTFN + ".subst" with open(substfilename, "w") as file: file.write(substfile) self.addCleanup(test_support.unlink, substfilename) argv = ["fixcid.py", "-s", substfilename] + list(args) script = os.path.join(scriptsdir, "fixcid.py") with test_support.swap_attr(sys, "argv", argv), \ test_support.swap_attr(sys, "stdin", StringIO(input)), \ test_support.captured_stdout() as output: try: runpy.run_path(script, run_name="__main__") except SystemExit as exit: self.assertEqual(exit.code, 0) return output.getvalue()
Example #5
Source File: profiler.py From vprof with BSD 2-Clause "Simplified" License | 6 votes |
def _profile_package(self): """Runs cProfile on a package.""" prof = cProfile.Profile() prof.enable() try: runpy.run_path(self._run_object, run_name='__main__') except SystemExit: pass prof.disable() prof_stats = pstats.Stats(prof) prof_stats.calc_callees() return { 'objectName': self._object_name, 'callStats': self._transform_stats(prof_stats), 'totalTime': prof_stats.total_tt, 'primitiveCalls': prof_stats.prim_calls, 'totalCalls': prof_stats.total_calls, 'timestamp': int(time.time()) }
Example #6
Source File: cli.py From click-odoo with GNU Lesser General Public License v3.0 | 6 votes |
def main(env, interactive, shell_interface, script, script_args): global_vars = {"env": env} if script: sys.argv[1:] = script_args global_vars = runpy.run_path( script, init_globals=global_vars, run_name="__main__" ) if not script or interactive: if console._isatty(sys.stdin): if not env: _logger.info("No environment set, use `-d dbname` to get one.") console.Shell.interact(global_vars, shell_interface) if env: env.cr.rollback() else: sys.argv[:] = [""] global_vars["__name__"] = "__main__" exec(sys.stdin.read(), global_vars)
Example #7
Source File: terraform_migrate_state.py From commcare-cloud with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_migrations(): file_names = sorted(os.listdir(MIGRATIONS_ROOT)) matcher = re.compile(r'^(\d\d\d\d)_(\w+)\.py') migrations = [] for file_name in file_names: match = matcher.match(file_name) if match: number_string, slug = match.groups() number = int(number_string) if number == 0: continue get_new_resource_address = runpy.run_path(os.path.join(MIGRATIONS_ROOT, file_name)).get('get_new_resource_address') migrations.append( Migration(number=number, slug=slug, get_new_resource_address=get_new_resource_address)) return migrations
Example #8
Source File: visualstudio_py_util.py From iot-utilities with BSD 3-Clause "New" or "Revised" License | 6 votes |
def exec_file(file, global_variables): '''Executes the provided script as if it were the original script provided to python.exe. The functionality is similar to `runpy.run_path`, which was added in Python 2.7/3.2. The following values in `global_variables` will be set to the following values, if they are not already set:: __name__ = '<run_path>' __file__ = file __package__ = __name__.rpartition('.')[0] # 2.6 and later __cached__ = None # 3.2 and later __loader__ = sys.modules['__main__'].__loader__ # 3.3 and later The `sys.modules` entry for ``__name__`` will be set to a new module, and ``sys.path[0]`` will be changed to the value of `file` without the filename. Both values are restored when this function exits. ''' f = open(file, "rb") try: code = f.read().replace(to_bytes('\r\n'), to_bytes('\n')) + to_bytes('\n') finally: f.close() exec_code(code, file, global_variables)
Example #9
Source File: visualstudio_py_util.py From iot-utilities with BSD 3-Clause "New" or "Revised" License | 6 votes |
def exec_file(file, global_variables): '''Executes the provided script as if it were the original script provided to python.exe. The functionality is similar to `runpy.run_path`, which was added in Python 2.7/3.2. The following values in `global_variables` will be set to the following values, if they are not already set:: __name__ = '<run_path>' __file__ = file __package__ = __name__.rpartition('.')[0] # 2.6 and later __cached__ = None # 3.2 and later __loader__ = sys.modules['__main__'].__loader__ # 3.3 and later The `sys.modules` entry for ``__name__`` will be set to a new module, and ``sys.path[0]`` will be changed to the value of `file` without the filename. Both values are restored when this function exits. ''' f = open(file, "rb") try: code = f.read().replace(to_bytes('\r\n'), to_bytes('\n')) + to_bytes('\n') finally: f.close() exec_code(code, file, global_variables)
Example #10
Source File: visualstudio_py_util.py From iot-utilities with BSD 3-Clause "New" or "Revised" License | 6 votes |
def exec_file(file, global_variables): '''Executes the provided script as if it were the original script provided to python.exe. The functionality is similar to `runpy.run_path`, which was added in Python 2.7/3.2. The following values in `global_variables` will be set to the following values, if they are not already set:: __name__ = '<run_path>' __file__ = file __package__ = __name__.rpartition('.')[0] # 2.6 and later __cached__ = None # 3.2 and later __loader__ = sys.modules['__main__'].__loader__ # 3.3 and later The `sys.modules` entry for ``__name__`` will be set to a new module, and ``sys.path[0]`` will be changed to the value of `file` without the filename. Both values are restored when this function exits. ''' f = open(file, "rb") try: code = f.read().replace(to_bytes('\r\n'), to_bytes('\n')) + to_bytes('\n') finally: f.close() exec_code(code, file, global_variables)
Example #11
Source File: cci.py From CumulusCI with BSD 3-Clause "New" or "Revised" License | 6 votes |
def shell(runtime, script=None, python=None): # alias for backwards-compatibility variables = { "config": runtime, "runtime": runtime, "project_config": runtime.project_config, } if script: if python: raise click.UsageError("Cannot specify both --script and --python") runpy.run_path(script, init_globals=variables) elif python: exec(python, variables) else: code.interact(local=variables)
Example #12
Source File: runner.py From kitty with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: cci.py From CumulusCI with BSD 3-Clause "New" or "Revised" License | 5 votes |
def org_shell(runtime, org_name, script=None, python=None): org_name, org_config = runtime.get_org(org_name) org_config.refresh_oauth_token(runtime.keychain) sf = get_simple_salesforce_connection(runtime.project_config, org_config) sf_helpers = SimpleSalesforceUIHelpers(sf) globals = { "sf": sf, "org_config": org_config, "project_config": runtime.project_config, "help": CCIHelp(), "query": sf_helpers.query, "describe": sf_helpers.describe, } if script: if python: raise click.UsageError("Cannot specify both --script and --python") runpy.run_path(script, init_globals=globals) elif python: exec(python, globals) else: code.interact( banner=f"Use `sf` to access org `{org_name}` via simple_salesforce\n" + "Type `help` for more information about the cci shell.", local=globals, ) # Save the org config in case it was modified runtime.keychain.set_org(org_config) # Commands for group: task
Example #14
Source File: spawn.py From Imogen with MIT License | 5 votes |
def _fixup_main_from_path(main_path): # If this process was forked, __main__ may already be populated current_main = sys.modules['__main__'] # Unfortunately, the main ipython launch script historically had no # "if __name__ == '__main__'" guard, so we work around that # by treating it like a __main__.py file # See https://github.com/ipython/ipython/issues/4698 main_name = os.path.splitext(os.path.basename(main_path))[0] if main_name == 'ipython': return # Otherwise, if __file__ already has the setting we expect, # there's nothing more to do if getattr(current_main, '__file__', None) == main_path: return # If the parent process has sent a path through rather than a module # name we assume it is an executable script that may contain # non-main code that needs to be executed old_main_modules.append(current_main) main_module = types.ModuleType("__mp_main__") main_content = runpy.run_path(main_path, run_name="__mp_main__") main_module.__dict__.update(main_content) sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
Example #15
Source File: marks.py From kitty with GNU General Public License v3.0 | 5 votes |
def marker_from_spec(ftype: str, spec: Union[str, Sequence[Tuple[int, str]]], flags: int) -> MarkerFunc: if ftype == 'regex': assert not isinstance(spec, str) if len(spec) == 1: return marker_from_regex(spec[0][1], spec[0][0], flags=flags) return marker_from_multiple_regex(spec, flags=flags) if ftype == 'function': import runpy assert isinstance(spec, str) path = spec if not os.path.isabs(path): path = os.path.join(config_dir, path) return marker_from_function(runpy.run_path(path, run_name='__marker__')["marker"]) raise ValueError('Unknown marker type: {}'.format(ftype))
Example #16
Source File: visualstudio_py_util.py From iot-utilities with BSD 3-Clause "New" or "Revised" License | 5 votes |
def exec_code(code, file, global_variables): '''Executes the provided code as if it were the original script provided to python.exe. The functionality is similar to `runpy.run_path`, which was added in Python 2.7/3.2. The following values in `global_variables` will be set to the following values, if they are not already set:: __name__ = '<run_path>' __file__ = file __package__ = __name__.rpartition('.')[0] # 2.6 and later __cached__ = None # 3.2 and later __loader__ = None # 3.3 and later The `sys.modules` entry for ``__name__`` will be set to a new module, and ``sys.path[0]`` will be changed to the value of `file` without the filename. Both values are restored when this function exits. ''' original_main = sys.modules.get('__main__') global_variables = dict(global_variables) mod_name = global_variables.setdefault('__name__', '<run_path>') mod = sys.modules[mod_name] = imp.new_module(mod_name) mod.__dict__.update(global_variables) global_variables = mod.__dict__ global_variables.setdefault('__file__', file) if sys.version_info[0] >= 3 or sys.version_info[1] >= 6: global_variables.setdefault('__package__', mod_name.rpartition('.')[0]) if sys.version_info[0] >= 3: if sys.version_info[1] >= 2: global_variables.setdefault('__cached__', None) if sys.version_info[1] >= 3: try: global_variables.setdefault('__loader__', original_main.__loader__) except AttributeError: pass sys.path[0] = os.path.split(file)[0] code_obj = compile(code, file, 'exec') exec(code_obj, global_variables)
Example #17
Source File: visualstudio_py_util.py From iot-utilities with BSD 3-Clause "New" or "Revised" License | 5 votes |
def exec_code(code, file, global_variables): '''Executes the provided code as if it were the original script provided to python.exe. The functionality is similar to `runpy.run_path`, which was added in Python 2.7/3.2. The following values in `global_variables` will be set to the following values, if they are not already set:: __name__ = '<run_path>' __file__ = file __package__ = __name__.rpartition('.')[0] # 2.6 and later __cached__ = None # 3.2 and later __loader__ = None # 3.3 and later The `sys.modules` entry for ``__name__`` will be set to a new module, and ``sys.path[0]`` will be changed to the value of `file` without the filename. Both values are restored when this function exits. ''' original_main = sys.modules.get('__main__') global_variables = dict(global_variables) mod_name = global_variables.setdefault('__name__', '<run_path>') mod = sys.modules[mod_name] = imp.new_module(mod_name) mod.__dict__.update(global_variables) global_variables = mod.__dict__ global_variables.setdefault('__file__', file) if sys.version_info[0] >= 3 or sys.version_info[1] >= 6: global_variables.setdefault('__package__', mod_name.rpartition('.')[0]) if sys.version_info[0] >= 3: if sys.version_info[1] >= 2: global_variables.setdefault('__cached__', None) if sys.version_info[1] >= 3: try: global_variables.setdefault('__loader__', original_main.__loader__) except AttributeError: pass sys.path[0] = os.path.split(file)[0] code_obj = compile(code, file, 'exec') exec(code_obj, global_variables)
Example #18
Source File: test_runpy.py From ironpython2 with Apache License 2.0 | 5 votes |
def _check_script(self, script_name, expected_name, expected_file, expected_argv0, expected_package): result = run_path(script_name) self.assertEqual(result["__name__"], expected_name) self.assertEqual(result["__file__"], expected_file) self.assertIn("argv0", result) self.assertEqual(result["argv0"], expected_argv0) self.assertEqual(result["__package__"], expected_package)
Example #19
Source File: visualstudio_py_util.py From iot-utilities with BSD 3-Clause "New" or "Revised" License | 5 votes |
def exec_code(code, file, global_variables): '''Executes the provided code as if it were the original script provided to python.exe. The functionality is similar to `runpy.run_path`, which was added in Python 2.7/3.2. The following values in `global_variables` will be set to the following values, if they are not already set:: __name__ = '<run_path>' __file__ = file __package__ = __name__.rpartition('.')[0] # 2.6 and later __cached__ = None # 3.2 and later __loader__ = None # 3.3 and later The `sys.modules` entry for ``__name__`` will be set to a new module, and ``sys.path[0]`` will be changed to the value of `file` without the filename. Both values are restored when this function exits. ''' original_main = sys.modules.get('__main__') global_variables = dict(global_variables) mod_name = global_variables.setdefault('__name__', '<run_path>') mod = sys.modules[mod_name] = imp.new_module(mod_name) mod.__dict__.update(global_variables) global_variables = mod.__dict__ global_variables.setdefault('__file__', file) if sys.version_info[0] >= 3 or sys.version_info[1] >= 6: global_variables.setdefault('__package__', mod_name.rpartition('.')[0]) if sys.version_info[0] >= 3: if sys.version_info[1] >= 2: global_variables.setdefault('__cached__', None) if sys.version_info[1] >= 3: try: global_variables.setdefault('__loader__', original_main.__loader__) except AttributeError: pass sys.path[0] = os.path.split(file)[0] code_obj = compile(code, file, 'exec') exec(code_obj, global_variables)
Example #20
Source File: test_runpy.py From ironpython2 with Apache License 2.0 | 5 votes |
def _check_import_error(self, script_name, msg): msg = re.escape(msg) self.assertRaisesRegexp(ImportError, msg, run_path, script_name)
Example #21
Source File: visualstudio_py_util.py From iot-utilities with BSD 3-Clause "New" or "Revised" License | 5 votes |
def exec_code(code, file, global_variables): '''Executes the provided code as if it were the original script provided to python.exe. The functionality is similar to `runpy.run_path`, which was added in Python 2.7/3.2. The following values in `global_variables` will be set to the following values, if they are not already set:: __name__ = '<run_path>' __file__ = file __package__ = __name__.rpartition('.')[0] # 2.6 and later __cached__ = None # 3.2 and later __loader__ = None # 3.3 and later The `sys.modules` entry for ``__name__`` will be set to a new module, and ``sys.path[0]`` will be changed to the value of `file` without the filename. Both values are restored when this function exits. ''' original_main = sys.modules.get('__main__') global_variables = dict(global_variables) mod_name = global_variables.setdefault('__name__', '<run_path>') mod = sys.modules[mod_name] = imp.new_module(mod_name) mod.__dict__.update(global_variables) global_variables = mod.__dict__ global_variables.setdefault('__file__', file) if sys.version_info[0] >= 3 or sys.version_info[1] >= 6: global_variables.setdefault('__package__', mod_name.rpartition('.')[0]) if sys.version_info[0] >= 3: if sys.version_info[1] >= 2: global_variables.setdefault('__cached__', None) if sys.version_info[1] >= 3: try: global_variables.setdefault('__loader__', original_main.__loader__) except AttributeError: pass sys.path[0] = os.path.split(file)[0] code_obj = compile(code, file, 'exec') exec(code_obj, global_variables)
Example #22
Source File: test_runpy.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_encoding(self): with temp_dir() as script_dir: filename = os.path.join(script_dir, 'script.py') with open(filename, 'w', encoding='latin1') as f: f.write(""" #coding:latin1 s = "non-ASCII: h\xe9" """) result = run_path(filename) self.assertEqual(result['s'], "non-ASCII: h\xe9")
Example #23
Source File: test_runpy.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_main_recursion_error(self): with temp_dir() as script_dir, temp_dir() as dummy_dir: mod_name = '__main__' source = ("import runpy\n" "runpy.run_path(%r)\n") % dummy_dir script_name = self._make_test_script(script_dir, mod_name, source) zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name) msg = "recursion depth exceeded" self.assertRaisesRegex(RecursionError, msg, run_path, zip_name)
Example #24
Source File: test_runpy.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_zipfile_compiled(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) compiled_name = py_compile.compile(script_name, doraise=True) zip_name, fname = make_zip_script(script_dir, 'test_zip', compiled_name) self._check_script(zip_name, "<run_path>", fname, zip_name, mod_name=mod_name, check_loader=False)
Example #25
Source File: test_runpy.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_zipfile(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name) self._check_script(zip_name, "<run_path>", fname, zip_name, mod_name=mod_name, check_loader=False)
Example #26
Source File: test_runpy.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_directory_compiled(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) compiled_name = py_compile.compile(script_name, doraise=True) os.remove(script_name) if not sys.dont_write_bytecode: legacy_pyc = make_legacy_pyc(script_name) self._check_script(script_dir, "<run_path>", legacy_pyc, script_dir, mod_name=mod_name)
Example #27
Source File: test_runpy.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_script_compiled(self): with temp_dir() as script_dir: mod_name = 'script' script_name = self._make_test_script(script_dir, mod_name) compiled_name = py_compile.compile(script_name, doraise=True) os.remove(script_name) self._check_script(compiled_name, "<run_path>", compiled_name, compiled_name, expect_spec=False)
Example #28
Source File: test_runpy.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_basic_script_no_suffix(self): with temp_dir() as script_dir: mod_name = 'script' script_name = self._make_test_script(script_dir, mod_name, omit_suffix=True) self._check_script(script_name, "<run_path>", script_name, script_name, expect_spec=False)
Example #29
Source File: test_runpy.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_basic_script(self): with temp_dir() as script_dir: mod_name = 'script' script_name = self._make_test_script(script_dir, mod_name) self._check_script(script_name, "<run_path>", script_name, script_name, expect_spec=False)
Example #30
Source File: test_runpy.py From ironpython3 with Apache License 2.0 | 5 votes |
def _check_import_error(self, script_name, msg): msg = re.escape(msg) self.assertRaisesRegex(ImportError, msg, run_path, script_name)