CPython interpreter modules import system is written in python itself and is initialized in importlib._bootstrap. Its source can be seen in importlib/_bootstrap.py, but it is not loaded from there. Instead it is loaded from so called frozen module, which bytecode is baked into the interpreter library (python37.dll).
The interpreter initializes itself by importing _frozen_importlib (it's a name for importlib._bootstrap baked into the interpreter) and calling _install function defined there, passing sys and _imp modules as arguments. _install calls _setup, which initializes runtime needed for this module, and then adds 2 importers, implementing PEP 451.
When developing a custom importer I have encountered several bugs either in _bootstrap.py or in my importer, so I need to add some debug output into _bootstrap.py.
So I try to make the interpreter to load _bootstrap.py from disk, not from baked-in bytecode.
Analysis of cpython source code revealed that in order to import builtin modules I don't need the most of spec class. So builtin modules can be imported using _create_builtin
class UltraSimpleSpec:
__slots__=("name",)
def __init__(self, name):
self.name = name
def _install(sys, _imp):
io = _imp.create_builtin(UltraSimpleSpec("_io"))
_bi = _imp.create_builtin(UltraSimpleSpec("builtins"))
fd = io.open("path/to/_bootstrap.py", "rt") # exits the _install function without any exception, how can it do it?
raise _bi.Exception("Never called") # _bi.print doesn't work, because sys.stdout is not initialized, so I have to use exceptions for debug output
...
Unfortunately something strange happens and call to io.open causes _install to exit, control flow never reaches the next statement. And no exception seems to be raised, when it is, interpreter prints it, instead an exception is raised in another place because of missing side effect of _install.
Yet ahother nuisance is that sys.stdout is not initialized, so we cannot print and have to rely on exceptions for debug output.
So
How should I make
openwork?How should I initialize
sys.stdout?