本文整理匯總了Python中runpy.run_module方法的典型用法代碼示例。如果您正苦於以下問題:Python runpy.run_module方法的具體用法?Python runpy.run_module怎麽用?Python runpy.run_module使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類runpy
的用法示例。
在下文中一共展示了runpy.run_module方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: main
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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()
示例2: _check_module
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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"
示例3: _check_package
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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"
示例4: test_train_word2vec_subword_jap
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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'])
示例5: _fixup_main_from_name
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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
示例6: run_kitten
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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)
示例7: handle
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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
示例8: handle
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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__')
示例9: run
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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_
示例10: test_run_name
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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)
示例11: expect_import_error
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
def expect_import_error(self, mod_name):
try:
run_module(mod_name)
except ImportError:
pass
else:
self.fail("Expected import error for " + mod_name)
示例12: test_library_module
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
def test_library_module(self):
run_module("runpy")
示例13: _check_relative_imports
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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 = (
self._make_pkg(contents, depth))
try:
self._add_relative_modules(pkg_dir, contents, depth)
pkg_name = mod_name.rpartition('.')[0]
if verbose: print "Running from source:", mod_name
d1 = run_module(mod_name, run_name=run_name) # Read from source
self.assertIn("__package__", d1)
self.assertTrue(d1["__package__"] == pkg_name)
self.assertIn("sibling", d1)
self.assertIn("nephew", d1)
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, run_name=run_name) # Read from bytecode
self.assertIn("__package__", d2)
self.assertTrue(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: print "Module executed successfully"
示例14: cmd_module
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
def cmd_module():
"executes module like `python -m`"
activate()
import runpy
sys.path.insert(0, '')
module = sys.argv[2]
sys.argv = [sys.argv[2]] + sys.argv[3:]
runpy.run_module(module, run_name='__main__')
示例15: safe_run_module
# 需要導入模塊: import runpy [as 別名]
# 或者: from runpy import run_module [as 別名]
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)