我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用runpy.run_path()。
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)
def run_cli_options(args): """ Quick implementation of Python interpreter's -m, -c and file execution. The resulting dictionary is imported into global namespace, just in case someone is using interactive mode. """ if not in_ipython(): if args.module: globals().update(runpy.run_module(args.module, run_name="__main__")) if args.string: exec(args.string) if args.command not in ('ipython', 'notebook', None): oldargv, sys.argv = sys.argv, sys.argv[1:] globals().update(runpy.run_path(args.command, run_name="__main__")) sys.argv = oldargv if _interactive_mode(args.interactive): os.environ['PYTHONINSPECT'] = '1'
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()
def _check_script(self, script_name, expected_name, expected_file, expected_argv0): # First check is without run_name def create_ns(init_globals): return run_path(script_name, init_globals) expected_ns = example_namespace.copy() expected_ns.update({ "__name__": expected_name, "__file__": expected_file, "__package__": "", "run_argv0": expected_argv0, "run_name_in_sys_modules": True, "module_in_sys_modules": True, }) self.check_code_execution(create_ns, expected_ns) # Second check makes sure run_name works in all cases run_name = "prove.issue15230.is.fixed" def create_ns(init_globals): return run_path(script_name, init_globals, run_name) expected_ns["__name__"] = run_name expected_ns["__package__"] = run_name.rpartition(".")[0] self.check_code_execution(create_ns, expected_ns)
def init(self): super(RespondCommand, self).init() self.init_link_attributes() if self.args.config is not None: config_file = self.args.config if config_file == "-": config_file = "/dev/stdin" try: config = _runpy.run_path(config_file) except: self.fail("Failed to load config from '{0}'", config_file) try: self.process = config["process"] except KeyError: self.fail("Function 'process' not found in '{0}'", config_file) self.desired_messages = self.args.count self.upper = self.args.upper self.reverse = self.args.reverse self.append = self.args.append
def main(): parser = create_parser() args = parser.parse_args() # Arguments that drive the behaviour of pyorcy pyorcy.USE_CYTHON = True if args.python: pyorcy.USE_CYTHON = False if args.verbose: pyorcy.VERBOSE = True # Add the location of the module to the sys.path module = args.MODULE[0] sys.path.append(os.path.dirname(module)) # Add remaining parameters in globals init_globals = {'__args__': args.mod_args} # Execute the module runpy.run_path(module, init_globals=init_globals, run_name="__main__")
def test_example(self, name, example): runpy.run_path(example, run_name='__main__') # Test algorithm as if scripts/run_algo.py is being used.
def run_handler(args: argparse.Namespace, stdout: IO, stderr: IO) -> None: # remove initial `monkeytype run` old_argv = sys.argv.copy() sys.argv = sys.argv[2:] try: with trace(args.config): runpy.run_path(args.script_path, run_name='__main__') finally: sys.argv = old_argv
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.assertEqual(result["__cached__"], None) self.assertIn("argv0", result) self.assertEqual(result["argv0"], expected_argv0) self.assertEqual(result["__package__"], expected_package)
def _check_import_error(self, script_name, msg): msg = re.escape(msg) self.assertRaisesRegex(ImportError, msg, run_path, script_name)
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, None)
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, None)
def test_directory(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) self._check_script(script_dir, "<run_path>", script_name, script_dir, '')
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, '')
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, '')
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(RuntimeError, msg, run_path, zip_name)
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 "non-ASCII: h\xe9" """) result = run_path(filename) self.assertEqual(result['__doc__'], "non-ASCII: h\xe9")
def __init__(self, file_path): self._config = run_path(file_path)
def load(self): """Load nodes and elements from all network files and return them in a :class:`~hydpy.selectiontools.Selections` instance. Each single network file defines a seperate :class:`~hydpy.selectiontools.Selection` instance. Additionally, all elements and nodes are bundled in a selection named `complete`. """ selections = selectiontools.Selections() for (filename, path) in zip(self.filenames, self.filepaths): # Ensure both `Node` and `Element`start with a `fresh` memory. devicetools.Node.gather_new_nodes() devicetools.Element.gather_new_elements() try: info = runpy.run_path(path) except Exception: prefix = 'While trying to load the network file `%s`' % path objecttools.augmentexcmessage(prefix) try: selections += selectiontools.Selection( filename.split('.')[0], info['Node'].gather_new_nodes(), info['Element'].gather_new_elements()) except KeyError as exc: KeyError('The class `%s` cannot be loaded from the network ' 'file `%s`. Please refer to the HydPy documentation ' 'on how to prepare network files properly.' % (exc.args[0], filename)) selections += selectiontools.Selection( 'complete', info['Node'].registered_nodes(), info['Element'].registered_elements()) return selections
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)
def _check_import_error(self, script_name, msg): msg = re.escape(msg) self.assertRaisesRegexp(ImportError, msg, run_path, script_name)
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 = compile_script(script_name) os.remove(script_name) self._check_script(compiled_name, "<run_path>", compiled_name, compiled_name, None)
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 = compile_script(script_name) zip_name, fname = make_zip_script(script_dir, 'test_zip', compiled_name) self._check_script(zip_name, "<run_path>", fname, zip_name, '')
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.assertRaisesRegexp(RuntimeError, msg, run_path, zip_name)
def load_calibration(): '''Load calibration data and calculate calibration values.''' # TODO: handle different calibration measurements, not just one for datadir global p1_cal, p2_cal try: # Load the variables in 'calibration.py'. calglobals = runpy.run_path( os.path.join(datadir, 'calibration.py') ) # Store the calibration data and the linear regression. p1_cal = dict(data=calglobals['p1_data']) try: p1_zero_idx = p1_cal['data']['refinputs'].index(0.0) p1_offset = p1_cal['data']['measurements'][p1_zero_idx] except IndexError: p1_offset = 0.0 p1_cal['regression'] = stats.linregress( np.array(p1_cal['data']['measurements']) - p1_offset, np.array(p1_cal['data']['refinputs']) ) p2_cal = dict(data=calglobals['p2_data']) try: p2_zero_idx = p2_cal['data']['refinputs'].index(0.0) p2_offset = p2_cal['data']['measurements'][p2_zero_idx] except IndexError: p2_offset = 0.0 p2_cal['regression'] = stats.linregress( np.array(p2_cal['data']['measurements']) - p2_offset, np.array(p2_cal['data']['refinputs']) ) except Exception as e: # TODO: print info/warning? print(e) p1_cal = None p2_cal = None print('p1_cal: ', p1_cal) print('p2_cal: ', p2_cal)
def get_version(): filename = os.path.join(os.path.dirname(__file__), "wpm", "__init__.py") var = runpy.run_path(filename) return var["__version__"]
def execute(self, args): '''???? ''' import runpy runpy.run_path(args.script_path, run_name='__main__')
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)
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)
def test_directory(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) self._check_script(script_dir, "<run_path>", script_name, script_dir)
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)