从<class'bytes'>而不是文件导入

2024-10-03 06:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我有一个.pyd共享库,它被加密为.epyd,我用它读取和解密

with open('src_nuitka/src.epyd', 'rb') as f:
     my_pyd_module = decrypt(f.read())

现在,我想直接使用<class 'bytes'>对象my_pyd_module导入模块,而不首先写入磁盘。我该怎么做?因为它不是Python代码字符串,所以我不能使用exec。是否有可用于此任务的导入挂钩?所有编写导入钩子的示例都是通过使用exec或直接实例化类(如https://dev.to/dangerontheranger/dependency-injection-with-import-hooks-in-python-3-5hap)来实现的


因此,这是我第一次尝试使用@a_guest和https://dev.to/dangerontheranger/dependency-injection-with-import-hooks-in-python-3-5hap的思想(目前还没有en-/解密):

import importlib.abc
import importlib.machinery
import sys

class DependencyInjectorFinder(importlib.abc.MetaPathFinder):
    def __init__(self, loader):
        self._loader: DependencyInjectorLoader = loader
    def find_spec(self, fullname, path, target=None):
        if fullname == 'src2':
            return importlib.machinery.ModuleSpec(fullname, self._loader)

class DependencyInjectorLoader(importlib.machinery.ExtensionFileLoader):
    def get_data(self, path):
        with open('src_packaged/src_dist/src.pyd', 'rb') as f:
            module = f.read()
        return module

sys.meta_path.append(DependencyInjectorFinder(DependencyInjectorLoader('src2', 'src2')))
import src2

导致

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad argument type for built-in operation

最后一行


Tags: inimportselfsrcdefwithloaderimportlib