Python has an opportunity to import zip module like this
import sys
sys.path.insert(0, "my_module.zip")
from my_module import my_function
my_function()
Is there a way to import this ZIP archive but from memory (bytes), not from filesystem? For example, like this
import sys
sys.path.insert(0, open("my_module.zip", "rb"))
from my_module import my_function
my_function()
Maybe there are some hooks or similar? I've found the similar question. But it's too old and doesn't work with Python 3.11 python load zip with modules from memory
EDIT:
my_module.py file
def my_function():
print("This is my function")
Add the file in ZIP archive with name my_module.zip and delete my_module.py
Test 1
import sys
sys.path.insert(0, "my_module.zip")
import my_module
my_module.my_function()
Output:
This is my function
Test 2
#represents your bytes
mem = None
with open('my_module.zip', 'rb') as z:
mem = z.read()
#actual script
from io import BytesIO
import sys
sys.path.insert(0, BytesIO(mem))
import my_module
my_module.my_function()
Output:
Traceback (most recent call last):
File "........", line 12, in <module>
import my_module
ModuleNotFoundError: No module named 'my_module'