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