You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确使用importlib.import_module?模块导入报错求助

关于importlib.import_module的使用问题及报错解决

问题描述

使用importlib.import_module导入解密后生成的Python模块时,触发ModuleNotFoundError错误。

代码示例

class Main:
    def __init__:
        self.appFileName=None
        self.appFileToPass=None


    def decrypt(self, string):
        return cryptocode.decrypt(string, localKey)

    def decrypFile(self, file):

        # decrpts the file 
        newFile=""
        with open(file) as f:
            line = f.readline()
            while line:
                line = f.readline()
                newFile+=str(self.decrypt(line))


        # creats a random name 
        alphaName=f"{''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(random.randint(9,12)))}"
        self.appFileName=f"{alphaName}.py"
        self.appFileToPass=alphaName

        # save file locally 
        with open(self.appFileName, 'w') as myprints:
            myprints.write(newFile)
        myprints.close()
        

    def run(self):
        self.decrypFile("fileToDecrypt")
        app=importlib.import_module(self.appFileName)

if __name__ == "__main__":
    main=Main()
    main.run()

错误信息

Exception ignored in thread started by: <bound method runApp of <__main__.my class>
Traceback (most recent call last):
  File "C:\Myfile.py", line 4747, in runApp
    app=importlib.import_module(self.appFileName))
  File "C:Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'appR'

解决步骤

1. 修正模块名参数

importlib.import_module要求传入不带.py后缀的模块名,而非完整文件名。你的代码中self.appFileName是带.py的文件名(如appR.py),Python会将其当作模块名查找,自然无法找到对应模块。

修改run方法中的导入逻辑,使用不带后缀的self.appFileToPass:

def run(self):
    self.decrypFile("fileToDecrypt")
    app=importlib.import_module(self.appFileToPass)

2. 确保模块在Python搜索路径内

Python会从sys.path列表中的路径查找模块,默认包含当前工作目录。如果生成的模块文件在其他路径,需先将该路径添加到sys.path:

import sys
import os

# 替换为你的模块文件所在路径
module_dir = os.path.abspath("/path/to/module/directory")
if module_dir not in sys.path:
    sys.path.append(module_dir)

3. 代码优化建议

  • 修复__init__方法的语法错误,改为def __init__(self):
  • 简化文件读取逻辑,避免漏读第一行:
    with open(file) as f:
        newFile = ''.join(str(self.decrypt(line)) for line in f)
    
  • 删除冗余的myprints.close(),with语句会自动处理文件关闭

内容的提问来源于stack exchange,提问作者Esteban G. Gutierrez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 13:10:25