diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 2266cc0a7..59cdbbd35 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -670,6 +670,11 @@ plugins are tracked: _disabled: - ... + # Identifiers of plugins for which python compatibility information will be ignored and + # the plugin considered compatible in any case. Only for development, do NOT use in production. + _forcedCompatible: + - ... + # The rest are individual plugin settings, each tracked by their identifier, e.g.: some_plugin: some_setting: true diff --git a/pytest.ini b/pytest.ini index b6cad3962..597e09bdb 100644 --- a/pytest.ini +++ b/pytest.ini @@ -2,3 +2,4 @@ testpaths = src tests addopts = --doctest-modules --doctest-repr=octoprint.util:pp + --ignore=src/octoprint/vendor diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 2cf6afb59..6308cbdfd 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -376,9 +376,12 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti import os + # we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins + import octoprint.plugins + logger = log.getLogger(__name__ + ".startup") - plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True), + plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), "octoprint.plugins", True), settings.getBaseFolder("plugins")] plugin_entry_points = ["octoprint.plugin"] plugin_disabled_list = settings.get(["plugins", "_disabled"]) @@ -397,13 +400,16 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti return True plugin_validators.append(validator) + compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"]) + from octoprint.plugin import plugin_manager pm = plugin_manager(init=True, plugin_folders=plugin_folders, plugin_entry_points=plugin_entry_points, plugin_disabled_list=plugin_disabled_list, plugin_blacklist=plugin_blacklist, - plugin_validators=plugin_validators) + plugin_validators=plugin_validators, + compatibility_ignored_list=compatibility_ignored_list) settings_overlays = dict() disabled_from_overlays = dict() diff --git a/src/octoprint/events.py b/src/octoprint/events.py index cae1b493d..efcbbe08b 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -230,7 +230,7 @@ class EventManager(object): if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables": # when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode" - # TODO v1.3.0 Remove again + # TODO v1.4.0 Remove again import copy legacy_payload = copy.deepcopy(payload) legacy_payload["type"] = "gcode" diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 06d29ee89..1893c950f 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -38,7 +38,7 @@ def _validate_plugin(phase, plugin_info): def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, - plugin_validators=None): + plugin_validators=None, compatibility_ignored_list=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` singleton. @@ -64,6 +64,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will not be enabled since they might depend on functionality that is no longer available. plugin_validators (list): A list of additional plugin validators through which to process each plugin. + compatibility_ignored_list (list): A list of plugin keys for which it will be ignored if they are flagged as + incompatible. This is for development purposes only and should not be used in production. Returns: PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin @@ -106,7 +108,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en plugin_blacklist=plugin_blacklist, plugin_restart_needing_hooks=plugin_restart_needing_hooks, plugin_obsolete_hooks=plugin_obsolete_hooks, - plugin_validators=plugin_validators) + plugin_validators=plugin_validators, + compatibility_ignored_list=compatibility_ignored_list) else: raise ValueError("Plugin Manager not initialized yet") return _instance diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index b97a6742d..40546fe3f 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -22,18 +22,17 @@ way and could be extracted into a separate Python module in the future. """ -__author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import os import io -import imp from collections import defaultdict, namedtuple, OrderedDict import logging import fnmatch import inspect +import sys import pkg_resources import pkginfo @@ -48,8 +47,33 @@ try: except ImportError: from scandir import scandir + +if sys.version_info[0] == 2: + # noinspection PyDeprecation + import imp +else: + # deprecated in Python 3.4+ and hence vendored for now + import octoprint.vendor.imp as imp + + +# noinspection PyDeprecation +def _find_module(name, path=None): + if path is not None: + spec = imp.find_module(name, [path]) + else: + spec = imp.find_module(name) + return spec[1], spec + + +# noinspection PyDeprecation +def _load_module(name, spec): + f, filename, details = spec + return imp.load_module(name, f, filename, details) + + EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version") FolderOrigin = namedtuple("FolderOrigin", "type, folder") +ModuleOrigin = namedtuple("PackageOrigin", "type, module_name, folder") class PluginInfo(object): """ @@ -166,6 +190,7 @@ class PluginInfo(object): self.loaded = False self.managable = True self.needs_restart = False + self.invalid_syntax = False self._name = name self._version = version @@ -177,12 +202,14 @@ class PluginInfo(object): self._logger = logging.getLogger(__name__) self._cached_parsed_metadata = parsed_metadata + if self._cached_parsed_metadata is None: + self._cached_parsed_metadata = self._parse_metadata() def validate(self, phase, additional_validators=None): result = True if phase == "before_import": - result = not self.forced_disabled and not self.blacklisted and not self.incompatible and result + result = not self.forced_disabled and not self.blacklisted and not self.incompatible and not self.invalid_syntax and result elif phase == "before_load": # if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__ @@ -524,8 +551,6 @@ class PluginInfo(object): @property def parsed_metadata(self): - if self._cached_parsed_metadata is None: - self._cached_parsed_metadata = self._parse_metadata() return self._cached_parsed_metadata def _parse_metadata(self): @@ -551,7 +576,7 @@ class PluginInfo(object): import ast with io.open(path, 'rb') as f: - root = ast.parse(f.read()) + root = ast.parse(f.read(), filename=path) assignments = list(filter(lambda x: isinstance(x, ast.Assign) and x.targets, root.body)) @@ -575,9 +600,11 @@ class PluginInfo(object): result[key] = a.value.args[0].s break + except SyntaxError: + self._logger.exception("Invalid syntax in {} for plugin {}".format(path, self.key)) + self.invalid_syntax = True except Exception: - # TODO: really ignore all errors? - pass + self._logger.exception("Error while parsing AST from {} for plugin {}".format(path, self.key)) return result @@ -592,7 +619,7 @@ class PluginManager(object): def __init__(self, plugin_folders, plugin_bases, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, - plugin_obsolete_hooks=None, plugin_validators=None): + plugin_obsolete_hooks=None, plugin_validators=None, compatibility_ignored_list=None): self.logger = logging.getLogger(__name__) if logging_prefix is None: @@ -607,6 +634,8 @@ class PluginManager(object): plugin_disabled_list = [] if plugin_blacklist is None: plugin_blacklist = [] + if compatibility_ignored_list is None: + compatibility_ignored_list = [] self.plugin_folders = plugin_folders self.plugin_bases = plugin_bases @@ -617,6 +646,7 @@ class PluginManager(object): self.plugin_obsolete_hooks = plugin_obsolete_hooks self.plugin_validators = plugin_validators self.logging_prefix = logging_prefix + self.compatibility_ignored_list = compatibility_ignored_list self.enabled_plugins = dict() self.disabled_plugins = dict() @@ -714,9 +744,12 @@ class PluginManager(object): for folder in folders: try: flagged_readonly = False + package = None if isinstance(folder, (list, tuple)): if len(folder) == 2: folder, flagged_readonly = folder + elif len(folder) == 3: + folder, package, flagged_readonly = folder else: continue actual_readonly = not os.access(folder, os.W_OK) @@ -754,9 +787,16 @@ class PluginManager(object): bundled = flagged_readonly - plugin = self._import_plugin_from_module(key, folder=folder, bundled=bundled) + module_name = None + if package: + module_name = "{}.{}".format(package, key) + + plugin = self._import_plugin_from_module(key, module_name=module_name, folder=folder, bundled=bundled) if plugin: - plugin.origin = FolderOrigin("folder", folder) + if module_name: + plugin.origin = ModuleOrigin("module", module_name, folder) + else: + plugin.origin = FolderOrigin("folder", folder) plugin.managable = not flagged_readonly and not actual_readonly plugin.enabled = False added[key] = plugin @@ -852,17 +892,17 @@ class PluginManager(object): # TODO error handling try: if folder: - module = imp.find_module(key, [folder]) + location, spec = _find_module(key, path=folder) elif module_name: - module = imp.find_module(module_name) + location, spec = _find_module(module_name) else: return None except Exception: - self.logger.warn("Could not locate plugin {key}".format(key=key)) + self.logger.exception("Could not locate plugin {key}".format(key=key)) return None # Create a simple dummy entry first ... - plugin = PluginInfo(key, module[1], None, name=name, version=version, description=summary, author=author, + plugin = PluginInfo(key, location, None, name=name, version=version, description=summary, author=author, url=url, license=license) plugin.bundled = bundled @@ -875,25 +915,30 @@ class PluginManager(object): plugin.blacklisted = True python_version = get_python_version_string() - if not is_python_compatible(plugin.pythoncompat) and not plugin.bundled: - self.logger.warning("Plugin {} is not compatible to Python {} (compatibility string: {}).".format(plugin, python_version, plugin.pythoncompat)) + if self._is_plugin_incompatible(key, plugin): + if plugin.invalid_syntax: + self.logger.warning("Plugin {} can't be compiled under Python {} due to invalid syntax".format(plugin, python_version)) + else: + self.logger.warning("Plugin {} is not compatible to Python {} (compatibility string: {}).".format(plugin, python_version, plugin.pythoncompat)) plugin.incompatible = True if not plugin.validate("before_import", additional_validators=self.plugin_validators): return plugin # ... then create and return the real one - return self._import_plugin(key, *module, - module_name=module_name, name=name, version=version, summary=summary, author=author, url=url, - license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata) + return self._import_plugin(key, spec, + module_name=module_name, name=name, location=plugin.location, version=version, + summary=summary, author=author, url=url, license=license, bundled=bundled, + parsed_metadata=plugin.parsed_metadata) - def _import_plugin(self, key, f, filename, description, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None): + def _import_plugin(self, key, spec, module_name=None, name=None, location=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None): try: if module_name: - instance = imp.load_module(module_name, f, filename, description) + module = _load_module(module_name, spec) else: - instance = imp.load_module(key, f, filename, description) - plugin = PluginInfo(key, filename, instance, + module = _load_module(key, spec) + + plugin = PluginInfo(key, location, module, name=name, version=version, description=summary, @@ -901,6 +946,7 @@ class PluginManager(object): url=url, license=license, parsed_metadata=parsed_metadata) + plugin.bundled = bundled except Exception: self.logger.exception("Error loading plugin {key}".format(key=key)) @@ -918,6 +964,11 @@ class PluginManager(object): def _is_plugin_blacklisted(self, key): return key in self.plugin_blacklist + def _is_plugin_incompatible(self, key, plugin): + return not plugin.bundled \ + and not is_python_compatible(plugin.pythoncompat) \ + and key not in self.compatibility_ignored_list + def _is_plugin_version_blacklisted(self, key, version): def matches_plugin(entry): if isinstance(entry, (tuple, list)) and len(entry) == 2: diff --git a/src/octoprint/plugins/__init__.py b/src/octoprint/plugins/__init__.py index a16150cde..092cd3e34 100644 --- a/src/octoprint/plugins/__init__.py +++ b/src/octoprint/plugins/__init__.py @@ -1,4 +1,2 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals - -# make our plugins testable diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 3fd9c2eb1..87f3f7b8d 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -302,15 +302,17 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, track_event = "print_started" elif event == Events.PRINT_DONE: try: - elapsed = int(payload.get("elapsed")) - args["elapsed"] = elapsed + elapsed = int(payload.get("elapsed", 0)) + if elapsed: + args["elapsed"] = elapsed except ValueError: pass track_event = "print_done" elif event == Events.PRINT_FAILED: try: - elapsed = int(payload.get("elapsed")) - args["elapsed"] = elapsed + elapsed = int(payload.get("elapsed", 0)) + if elapsed: + args["elapsed"] = elapsed except ValueError: pass args["reason"] = payload.get("reason", "unknown") @@ -321,8 +323,9 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, track_event = "print_failed" elif event == Events.PRINT_CANCELLED: try: - elapsed = int(payload.get("time")) - args["elapsed"] = elapsed + elapsed = int(payload.get("time", 0)) + if elapsed: + args["elapsed"] = elapsed except ValueError: pass track_event = "print_cancelled" diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 5d305db9f..e9b665636 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -367,7 +367,8 @@ default_settings = { { "name": "Suppress wait responses", "regex": "Recv: wait"} ], "plugins": { - "_disabled": [] + "_disabled": [], + "_forcedCompatible": [] }, "scripts": { "gcode": { diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index d50db850c..50e37c951 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -934,7 +934,7 @@ $(function() { return; } - if (payload.type !== "gcode") { + if (payload.type !== "printables") { return; } diff --git a/src/octoprint/vendor/imp.py b/src/octoprint/vendor/imp.py new file mode 100644 index 000000000..921445ce4 --- /dev/null +++ b/src/octoprint/vendor/imp.py @@ -0,0 +1,331 @@ +"""This module provides the components needed to build your own __import__ +function. Undocumented functions are obsolete. + +In most cases it is preferred you consider using the importlib module's +functionality over this module. + +Taken from CPython 3.7.0 and vendored to still have it when it gets +completely removed. + +Licensed under the PSF LICENSE AGREEMENT +""" + +import sys +assert sys.version_info[0] == 3 and sys.version_info[1] >= 5 # this only works on Python 3.5+ + +# (Probably) need to stay in _imp +# noinspection PyCompatibility +from _imp import (lock_held, acquire_lock, release_lock, + get_frozen_object, is_frozen_package, + init_frozen, is_builtin, is_frozen, + _fix_co_filename) +try: + # noinspection PyCompatibility + from _imp import create_dynamic +except ImportError: + # Platform doesn't support dynamic loading. + create_dynamic = None + +# noinspection PyCompatibility,PyProtectedMember +from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name + +# noinspection PyCompatibility,PyProtectedMember +from importlib._bootstrap_external import SourcelessFileLoader + +# noinspection PyCompatibility +from importlib import machinery +# noinspection PyCompatibility +from importlib import util +import importlib +import os +import sys +import tokenize +import types +import warnings + +SEARCH_ERROR = 0 +PY_SOURCE = 1 +PY_COMPILED = 2 +C_EXTENSION = 3 +PY_RESOURCE = 4 +PKG_DIRECTORY = 5 +C_BUILTIN = 6 +PY_FROZEN = 7 +PY_CODERESOURCE = 8 +IMP_HOOK = 9 + + +def new_module(name): + """Create a new module. + + The module is not entered into sys.modules. + + """ + # noinspection PyUnresolvedReferences + return types.ModuleType(name) + + +def get_magic(): + """Return the magic number for .pyc files. + """ + return util.MAGIC_NUMBER + + +def get_tag(): + """Return the magic tag for .pyc files.""" + return sys.implementation.cache_tag + + +def cache_from_source(path, debug_override=None): + """Given the path to a .py file, return the path to its .pyc file. + + The .py file does not need to exist; this simply returns the path to the + .pyc file calculated as if the .py file were imported. + + If debug_override is not None, then it must be a boolean and is used in + place of sys.flags.optimize. + + If sys.implementation.cache_tag is None then NotImplementedError is raised. + + """ + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + return util.cache_from_source(path, debug_override) + + +def source_from_cache(path): + """Given the path to a .pyc. file, return the path to its .py file. + + The .pyc file does not need to exist; this simply returns the path to + the .py file calculated to correspond to the .pyc file. If path does + not conform to PEP 3147 format, ValueError will be raised. If + sys.implementation.cache_tag is None then NotImplementedError is raised. + + """ + return util.source_from_cache(path) + + +def get_suffixes(): + extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES] + source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES] + bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES] + + return extensions + source + bytecode + + +class NullImporter: + + """Null import object.""" + + def __init__(self, path): + if path == '': + raise ImportError('empty pathname', path='') + elif os.path.isdir(path): + raise ImportError('existing directory', path=path) + + def find_module(self, fullname): + """Always returns None.""" + return None + + +# noinspection PyCompatibility,PyUnresolvedReferences +class _HackedGetData: + + """Compatibility support for 'file' arguments of various load_*() + functions.""" + + def __init__(self, fullname, path, file=None): + super().__init__(fullname, path) + self.file = file + + def get_data(self, path): + """Gross hack to contort loader to deal w/ load_*()'s bad API.""" + if self.file and path == self.path: + if not self.file.closed: + file = self.file + else: + self.file = file = open(self.path, 'r') + + with file: + # Technically should be returning bytes, but + # SourceLoader.get_code() just passed what is returned to + # compile() which can handle str. And converting to bytes would + # require figuring out the encoding to decode to and + # tokenize.detect_encoding() only accepts bytes. + return file.read() + else: + return super().get_data(path) + + +class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader): + + """Compatibility support for implementing load_source().""" + + +def load_source(name, pathname, file=None): + loader = _LoadSourceCompatibility(name, pathname, file) + spec = util.spec_from_file_location(name, pathname, loader=loader) + if name in sys.modules: + module = _exec(spec, sys.modules[name]) + else: + module = _load(spec) + # To allow reloading to potentially work, use a non-hacked loader which + # won't rely on a now-closed file object. + module.__loader__ = machinery.SourceFileLoader(name, pathname) + module.__spec__.loader = module.__loader__ + return module + + +class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader): + + """Compatibility support for implementing load_compiled().""" + + +def load_compiled(name, pathname, file=None): + """**DEPRECATED**""" + loader = _LoadCompiledCompatibility(name, pathname, file) + spec = util.spec_from_file_location(name, pathname, loader=loader) + if name in sys.modules: + module = _exec(spec, sys.modules[name]) + else: + module = _load(spec) + # To allow reloading to potentially work, use a non-hacked loader which + # won't rely on a now-closed file object. + module.__loader__ = SourcelessFileLoader(name, pathname) + module.__spec__.loader = module.__loader__ + return module + + +def load_package(name, path): + if os.path.isdir(path): + extensions = (machinery.SOURCE_SUFFIXES[:] + + machinery.BYTECODE_SUFFIXES[:]) + for extension in extensions: + init_path = os.path.join(path, '__init__' + extension) + if os.path.exists(init_path): + path = init_path + break + else: + raise ValueError('{!r} is not a package'.format(path)) + spec = util.spec_from_file_location(name, path, + submodule_search_locations=[]) + if name in sys.modules: + return _exec(spec, sys.modules[name]) + else: + return _load(spec) + + +def load_module(name, file, filename, details): + """Load a module, given information returned by find_module(). + + The module name must include the full package name, if any. + + """ + suffix, mode, type_ = details + if mode and (not mode.startswith(('r', 'U')) or '+' in mode): + raise ValueError('invalid file open mode {!r}'.format(mode)) + elif file is None and type_ in {PY_SOURCE, PY_COMPILED}: + msg = 'file object required for import (type code {})'.format(type_) + raise ValueError(msg) + elif type_ == PY_SOURCE: + return load_source(name, filename, file) + elif type_ == PY_COMPILED: + return load_compiled(name, filename, file) + elif type_ == C_EXTENSION and load_dynamic is not None: + if file is None: + with open(filename, 'rb') as opened_file: + return load_dynamic(name, filename, opened_file) + else: + return load_dynamic(name, filename, file) + elif type_ == PKG_DIRECTORY: + return load_package(name, filename) + elif type_ == C_BUILTIN: + return init_builtin(name) + elif type_ == PY_FROZEN: + return init_frozen(name) + else: + msg = "Don't know how to import {} (type code {})".format(name, type_) + raise ImportError(msg, name=name) + + +def find_module(name, path=None): + """Search for a module. + + If path is omitted or None, search for a built-in, frozen or special + module and continue search in sys.path. The module name cannot + contain '.'; to search for a submodule of a package, pass the + submodule name and the package's __path__. + + """ + if not isinstance(name, str): + raise TypeError("'name' must be a str, not {}".format(type(name))) + elif not isinstance(path, (type(None), list)): + # Backwards-compatibility + raise RuntimeError("'path' must be None or a list, " + "not {}".format(type(path))) + + if path is None: + if is_builtin(name): + return None, None, ('', '', C_BUILTIN) + elif is_frozen(name): + return None, None, ('', '', PY_FROZEN) + else: + path = sys.path + + for entry in path: + package_directory = os.path.join(entry, name) + for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]: + package_file_name = '__init__' + suffix + file_path = os.path.join(package_directory, package_file_name) + if os.path.isfile(file_path): + return None, package_directory, ('', '', PKG_DIRECTORY) + for suffix, mode, type_ in get_suffixes(): + file_name = name + suffix + file_path = os.path.join(entry, file_name) + if os.path.isfile(file_path): + break + else: + continue + break # Break out of outer loop when breaking out of inner loop. + else: + raise ImportError(_ERR_MSG.format(name), name=name) + + encoding = None + if 'b' not in mode: + with open(file_path, 'rb') as file: + encoding = tokenize.detect_encoding(file.readline)[0] + file = open(file_path, mode, encoding=encoding) + return file, file_path, (suffix, mode, type_) + + +def reload(module): + """Reload the module and return it. + + The module must have been successfully imported before. + + """ + return importlib.reload(module) + + +def init_builtin(name): + """Load and return a built-in module by name, or None is such module doesn't exist""" + try: + return _builtin_from_name(name) + except ImportError: + return None + + +if create_dynamic: + def load_dynamic(name, path, file=None): + """Load an extension module.""" + import importlib.machinery + loader = importlib.machinery.ExtensionFileLoader(name, path) + + # Issue #24748: Skip the sys.modules check in _load_module_shim; + # always load new extension + spec = importlib.machinery.ModuleSpec( + name=name, loader=loader, origin=path) + return _load(spec) + +else: + load_dynamic = None