Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../usr/lib64/python3....
File: runpy.py
"""runpy.py - locating and running Python code using the module namespace
[0] Fix | Delete
[1] Fix | Delete
Provides support for locating and running Python scripts using the Python
[2] Fix | Delete
module namespace instead of the native filesystem.
[3] Fix | Delete
[4] Fix | Delete
This allows Python code to play nicely with non-filesystem based PEP 302
[5] Fix | Delete
importers when locating support scripts as well as when importing modules.
[6] Fix | Delete
"""
[7] Fix | Delete
# Written by Nick Coghlan <ncoghlan at gmail.com>
[8] Fix | Delete
# to implement PEP 338 (Executing Modules as Scripts)
[9] Fix | Delete
[10] Fix | Delete
[11] Fix | Delete
import sys
[12] Fix | Delete
import importlib.machinery # importlib first so we can test #15386 via -m
[13] Fix | Delete
import importlib.util
[14] Fix | Delete
import types
[15] Fix | Delete
from pkgutil import read_code, get_importer
[16] Fix | Delete
[17] Fix | Delete
__all__ = [
[18] Fix | Delete
"run_module", "run_path",
[19] Fix | Delete
]
[20] Fix | Delete
[21] Fix | Delete
class _TempModule(object):
[22] Fix | Delete
"""Temporarily replace a module in sys.modules with an empty namespace"""
[23] Fix | Delete
def __init__(self, mod_name):
[24] Fix | Delete
self.mod_name = mod_name
[25] Fix | Delete
self.module = types.ModuleType(mod_name)
[26] Fix | Delete
self._saved_module = []
[27] Fix | Delete
[28] Fix | Delete
def __enter__(self):
[29] Fix | Delete
mod_name = self.mod_name
[30] Fix | Delete
try:
[31] Fix | Delete
self._saved_module.append(sys.modules[mod_name])
[32] Fix | Delete
except KeyError:
[33] Fix | Delete
pass
[34] Fix | Delete
sys.modules[mod_name] = self.module
[35] Fix | Delete
return self
[36] Fix | Delete
[37] Fix | Delete
def __exit__(self, *args):
[38] Fix | Delete
if self._saved_module:
[39] Fix | Delete
sys.modules[self.mod_name] = self._saved_module[0]
[40] Fix | Delete
else:
[41] Fix | Delete
del sys.modules[self.mod_name]
[42] Fix | Delete
self._saved_module = []
[43] Fix | Delete
[44] Fix | Delete
class _ModifiedArgv0(object):
[45] Fix | Delete
def __init__(self, value):
[46] Fix | Delete
self.value = value
[47] Fix | Delete
self._saved_value = self._sentinel = object()
[48] Fix | Delete
[49] Fix | Delete
def __enter__(self):
[50] Fix | Delete
if self._saved_value is not self._sentinel:
[51] Fix | Delete
raise RuntimeError("Already preserving saved value")
[52] Fix | Delete
self._saved_value = sys.argv[0]
[53] Fix | Delete
sys.argv[0] = self.value
[54] Fix | Delete
[55] Fix | Delete
def __exit__(self, *args):
[56] Fix | Delete
self.value = self._sentinel
[57] Fix | Delete
sys.argv[0] = self._saved_value
[58] Fix | Delete
[59] Fix | Delete
# TODO: Replace these helpers with importlib._bootstrap_external functions.
[60] Fix | Delete
def _run_code(code, run_globals, init_globals=None,
[61] Fix | Delete
mod_name=None, mod_spec=None,
[62] Fix | Delete
pkg_name=None, script_name=None):
[63] Fix | Delete
"""Helper to run code in nominated namespace"""
[64] Fix | Delete
if init_globals is not None:
[65] Fix | Delete
run_globals.update(init_globals)
[66] Fix | Delete
if mod_spec is None:
[67] Fix | Delete
loader = None
[68] Fix | Delete
fname = script_name
[69] Fix | Delete
cached = None
[70] Fix | Delete
else:
[71] Fix | Delete
loader = mod_spec.loader
[72] Fix | Delete
fname = mod_spec.origin
[73] Fix | Delete
cached = mod_spec.cached
[74] Fix | Delete
if pkg_name is None:
[75] Fix | Delete
pkg_name = mod_spec.parent
[76] Fix | Delete
run_globals.update(__name__ = mod_name,
[77] Fix | Delete
__file__ = fname,
[78] Fix | Delete
__cached__ = cached,
[79] Fix | Delete
__doc__ = None,
[80] Fix | Delete
__loader__ = loader,
[81] Fix | Delete
__package__ = pkg_name,
[82] Fix | Delete
__spec__ = mod_spec)
[83] Fix | Delete
exec(code, run_globals)
[84] Fix | Delete
return run_globals
[85] Fix | Delete
[86] Fix | Delete
def _run_module_code(code, init_globals=None,
[87] Fix | Delete
mod_name=None, mod_spec=None,
[88] Fix | Delete
pkg_name=None, script_name=None):
[89] Fix | Delete
"""Helper to run code in new namespace with sys modified"""
[90] Fix | Delete
fname = script_name if mod_spec is None else mod_spec.origin
[91] Fix | Delete
with _TempModule(mod_name) as temp_module, _ModifiedArgv0(fname):
[92] Fix | Delete
mod_globals = temp_module.module.__dict__
[93] Fix | Delete
_run_code(code, mod_globals, init_globals,
[94] Fix | Delete
mod_name, mod_spec, pkg_name, script_name)
[95] Fix | Delete
# Copy the globals of the temporary module, as they
[96] Fix | Delete
# may be cleared when the temporary module goes away
[97] Fix | Delete
return mod_globals.copy()
[98] Fix | Delete
[99] Fix | Delete
# Helper to get the full name, spec and code for a module
[100] Fix | Delete
def _get_module_details(mod_name, error=ImportError):
[101] Fix | Delete
if mod_name.startswith("."):
[102] Fix | Delete
raise error("Relative module names not supported")
[103] Fix | Delete
pkg_name, _, _ = mod_name.rpartition(".")
[104] Fix | Delete
if pkg_name:
[105] Fix | Delete
# Try importing the parent to avoid catching initialization errors
[106] Fix | Delete
try:
[107] Fix | Delete
__import__(pkg_name)
[108] Fix | Delete
except ImportError as e:
[109] Fix | Delete
# If the parent or higher ancestor package is missing, let the
[110] Fix | Delete
# error be raised by find_spec() below and then be caught. But do
[111] Fix | Delete
# not allow other errors to be caught.
[112] Fix | Delete
if e.name is None or (e.name != pkg_name and
[113] Fix | Delete
not pkg_name.startswith(e.name + ".")):
[114] Fix | Delete
raise
[115] Fix | Delete
# Warn if the module has already been imported under its normal name
[116] Fix | Delete
existing = sys.modules.get(mod_name)
[117] Fix | Delete
if existing is not None and not hasattr(existing, "__path__"):
[118] Fix | Delete
from warnings import warn
[119] Fix | Delete
msg = "{mod_name!r} found in sys.modules after import of " \
[120] Fix | Delete
"package {pkg_name!r}, but prior to execution of " \
[121] Fix | Delete
"{mod_name!r}; this may result in unpredictable " \
[122] Fix | Delete
"behaviour".format(mod_name=mod_name, pkg_name=pkg_name)
[123] Fix | Delete
warn(RuntimeWarning(msg))
[124] Fix | Delete
[125] Fix | Delete
try:
[126] Fix | Delete
spec = importlib.util.find_spec(mod_name)
[127] Fix | Delete
except (ImportError, AttributeError, TypeError, ValueError) as ex:
[128] Fix | Delete
# This hack fixes an impedance mismatch between pkgutil and
[129] Fix | Delete
# importlib, where the latter raises other errors for cases where
[130] Fix | Delete
# pkgutil previously raised ImportError
[131] Fix | Delete
msg = "Error while finding module specification for {!r} ({}: {})"
[132] Fix | Delete
raise error(msg.format(mod_name, type(ex).__name__, ex)) from ex
[133] Fix | Delete
if spec is None:
[134] Fix | Delete
raise error("No module named %s" % mod_name)
[135] Fix | Delete
if spec.submodule_search_locations is not None:
[136] Fix | Delete
if mod_name == "__main__" or mod_name.endswith(".__main__"):
[137] Fix | Delete
raise error("Cannot use package as __main__ module")
[138] Fix | Delete
try:
[139] Fix | Delete
pkg_main_name = mod_name + ".__main__"
[140] Fix | Delete
return _get_module_details(pkg_main_name, error)
[141] Fix | Delete
except error as e:
[142] Fix | Delete
if mod_name not in sys.modules:
[143] Fix | Delete
raise # No module loaded; being a package is irrelevant
[144] Fix | Delete
raise error(("%s; %r is a package and cannot " +
[145] Fix | Delete
"be directly executed") %(e, mod_name))
[146] Fix | Delete
loader = spec.loader
[147] Fix | Delete
if loader is None:
[148] Fix | Delete
raise error("%r is a namespace package and cannot be executed"
[149] Fix | Delete
% mod_name)
[150] Fix | Delete
try:
[151] Fix | Delete
code = loader.get_code(mod_name)
[152] Fix | Delete
except ImportError as e:
[153] Fix | Delete
raise error(format(e)) from e
[154] Fix | Delete
if code is None:
[155] Fix | Delete
raise error("No code object available for %s" % mod_name)
[156] Fix | Delete
return mod_name, spec, code
[157] Fix | Delete
[158] Fix | Delete
class _Error(Exception):
[159] Fix | Delete
"""Error that _run_module_as_main() should report without a traceback"""
[160] Fix | Delete
[161] Fix | Delete
# XXX ncoghlan: Should this be documented and made public?
[162] Fix | Delete
# (Current thoughts: don't repeat the mistake that lead to its
[163] Fix | Delete
# creation when run_module() no longer met the needs of
[164] Fix | Delete
# mainmodule.c, but couldn't be changed because it was public)
[165] Fix | Delete
def _run_module_as_main(mod_name, alter_argv=True):
[166] Fix | Delete
"""Runs the designated module in the __main__ namespace
[167] Fix | Delete
[168] Fix | Delete
Note that the executed module will have full access to the
[169] Fix | Delete
__main__ namespace. If this is not desirable, the run_module()
[170] Fix | Delete
function should be used to run the module code in a fresh namespace.
[171] Fix | Delete
[172] Fix | Delete
At the very least, these variables in __main__ will be overwritten:
[173] Fix | Delete
__name__
[174] Fix | Delete
__file__
[175] Fix | Delete
__cached__
[176] Fix | Delete
__loader__
[177] Fix | Delete
__package__
[178] Fix | Delete
"""
[179] Fix | Delete
try:
[180] Fix | Delete
if alter_argv or mod_name != "__main__": # i.e. -m switch
[181] Fix | Delete
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
[182] Fix | Delete
else: # i.e. directory or zipfile execution
[183] Fix | Delete
mod_name, mod_spec, code = _get_main_module_details(_Error)
[184] Fix | Delete
except _Error as exc:
[185] Fix | Delete
msg = "%s: %s" % (sys.executable, exc)
[186] Fix | Delete
sys.exit(msg)
[187] Fix | Delete
main_globals = sys.modules["__main__"].__dict__
[188] Fix | Delete
if alter_argv:
[189] Fix | Delete
sys.argv[0] = mod_spec.origin
[190] Fix | Delete
return _run_code(code, main_globals, None,
[191] Fix | Delete
"__main__", mod_spec)
[192] Fix | Delete
[193] Fix | Delete
def run_module(mod_name, init_globals=None,
[194] Fix | Delete
run_name=None, alter_sys=False):
[195] Fix | Delete
"""Execute a module's code without importing it
[196] Fix | Delete
[197] Fix | Delete
Returns the resulting top level namespace dictionary
[198] Fix | Delete
"""
[199] Fix | Delete
mod_name, mod_spec, code = _get_module_details(mod_name)
[200] Fix | Delete
if run_name is None:
[201] Fix | Delete
run_name = mod_name
[202] Fix | Delete
if alter_sys:
[203] Fix | Delete
return _run_module_code(code, init_globals, run_name, mod_spec)
[204] Fix | Delete
else:
[205] Fix | Delete
# Leave the sys module alone
[206] Fix | Delete
return _run_code(code, {}, init_globals, run_name, mod_spec)
[207] Fix | Delete
[208] Fix | Delete
def _get_main_module_details(error=ImportError):
[209] Fix | Delete
# Helper that gives a nicer error message when attempting to
[210] Fix | Delete
# execute a zipfile or directory by invoking __main__.py
[211] Fix | Delete
# Also moves the standard __main__ out of the way so that the
[212] Fix | Delete
# preexisting __loader__ entry doesn't cause issues
[213] Fix | Delete
main_name = "__main__"
[214] Fix | Delete
saved_main = sys.modules[main_name]
[215] Fix | Delete
del sys.modules[main_name]
[216] Fix | Delete
try:
[217] Fix | Delete
return _get_module_details(main_name)
[218] Fix | Delete
except ImportError as exc:
[219] Fix | Delete
if main_name in str(exc):
[220] Fix | Delete
raise error("can't find %r module in %r" %
[221] Fix | Delete
(main_name, sys.path[0])) from exc
[222] Fix | Delete
raise
[223] Fix | Delete
finally:
[224] Fix | Delete
sys.modules[main_name] = saved_main
[225] Fix | Delete
[226] Fix | Delete
[227] Fix | Delete
def _get_code_from_file(run_name, fname):
[228] Fix | Delete
# Check for a compiled file first
[229] Fix | Delete
with open(fname, "rb") as f:
[230] Fix | Delete
code = read_code(f)
[231] Fix | Delete
if code is None:
[232] Fix | Delete
# That didn't work, so try it as normal source code
[233] Fix | Delete
with open(fname, "rb") as f:
[234] Fix | Delete
code = compile(f.read(), fname, 'exec')
[235] Fix | Delete
return code, fname
[236] Fix | Delete
[237] Fix | Delete
def run_path(path_name, init_globals=None, run_name=None):
[238] Fix | Delete
"""Execute code located at the specified filesystem location
[239] Fix | Delete
[240] Fix | Delete
Returns the resulting top level namespace dictionary
[241] Fix | Delete
[242] Fix | Delete
The file path may refer directly to a Python script (i.e.
[243] Fix | Delete
one that could be directly executed with execfile) or else
[244] Fix | Delete
it may refer to a zipfile or directory containing a top
[245] Fix | Delete
level __main__.py script.
[246] Fix | Delete
"""
[247] Fix | Delete
if run_name is None:
[248] Fix | Delete
run_name = "<run_path>"
[249] Fix | Delete
pkg_name = run_name.rpartition(".")[0]
[250] Fix | Delete
importer = get_importer(path_name)
[251] Fix | Delete
# Trying to avoid importing imp so as to not consume the deprecation warning.
[252] Fix | Delete
is_NullImporter = False
[253] Fix | Delete
if type(importer).__module__ == 'imp':
[254] Fix | Delete
if type(importer).__name__ == 'NullImporter':
[255] Fix | Delete
is_NullImporter = True
[256] Fix | Delete
if isinstance(importer, type(None)) or is_NullImporter:
[257] Fix | Delete
# Not a valid sys.path entry, so run the code directly
[258] Fix | Delete
# execfile() doesn't help as we want to allow compiled files
[259] Fix | Delete
code, fname = _get_code_from_file(run_name, path_name)
[260] Fix | Delete
return _run_module_code(code, init_globals, run_name,
[261] Fix | Delete
pkg_name=pkg_name, script_name=fname)
[262] Fix | Delete
else:
[263] Fix | Delete
# Finder is defined for path, so add it to
[264] Fix | Delete
# the start of sys.path
[265] Fix | Delete
sys.path.insert(0, path_name)
[266] Fix | Delete
try:
[267] Fix | Delete
# Here's where things are a little different from the run_module
[268] Fix | Delete
# case. There, we only had to replace the module in sys while the
[269] Fix | Delete
# code was running and doing so was somewhat optional. Here, we
[270] Fix | Delete
# have no choice and we have to remove it even while we read the
[271] Fix | Delete
# code. If we don't do this, a __loader__ attribute in the
[272] Fix | Delete
# existing __main__ module may prevent location of the new module.
[273] Fix | Delete
mod_name, mod_spec, code = _get_main_module_details()
[274] Fix | Delete
with _TempModule(run_name) as temp_module, \
[275] Fix | Delete
_ModifiedArgv0(path_name):
[276] Fix | Delete
mod_globals = temp_module.module.__dict__
[277] Fix | Delete
return _run_code(code, mod_globals, init_globals,
[278] Fix | Delete
run_name, mod_spec, pkg_name).copy()
[279] Fix | Delete
finally:
[280] Fix | Delete
try:
[281] Fix | Delete
sys.path.remove(path_name)
[282] Fix | Delete
except ValueError:
[283] Fix | Delete
pass
[284] Fix | Delete
[285] Fix | Delete
[286] Fix | Delete
if __name__ == "__main__":
[287] Fix | Delete
# Run the module specified as the next command line argument
[288] Fix | Delete
if len(sys.argv) < 2:
[289] Fix | Delete
print("No module specified for execution", file=sys.stderr)
[290] Fix | Delete
else:
[291] Fix | Delete
del sys.argv[0] # Make the requested module sys.argv[0]
[292] Fix | Delete
_run_module_as_main(sys.argv[0])
[293] Fix | Delete
[294] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function