python - 如何修复在 python 中找不到的模块

标签 python python-3.x

我的 target.py 文件在 Starterpack/ModulesAndPackages/target.py 我的脚本文件在 Starterpack/Scripts/Bad.py

我的 ModulesAndPackages 文件夹有 __init__.py 文件,但是当我输入 from 时,我仍然收到此错误 No module named ModulesAndPackages ModulesAndPackages.target 在脚本文件中导入Target

我已经尝试了 sys.path.append()sys.path.insert() 但都没有用。在我的编辑器中没有错误,但是当我运行它时,它给出了错误。

脚本文件:

mandp_dir = "./ModulesAndPackages"
scripts_dir = "./Scripts"
main_dir = ".."

os.chdir(Path(main_dir))
from ModulesAndPackages.target import Target

target.py 文件:

import time
import os
import keyboard

class Target():
    def __init__(self, ip, port, packetsize, time=None):
        self.ip = ip
        self.port = port
        self.packetsize = packetsize
        self.time = time

    def attack(self):
        pass

如果我添加了 __init__.py 文件,我希望它能工作,但它没有。

最佳答案

您可能想将目录添加到 python 搜索路径,而不是更改当前目录,例如:

scripts_dir = "./Scripts"
main_dir = ".."

sys.path.append(Path(main_dir))

另外,检查一下:python-best-way-to-add-to-sys-path-relative-to-the-current-running-script

关于python - 如何修复在 python 中找不到的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57372656/

相关文章:

python-3.x - 套接字错误 : [Errno 49] Can't assign requested address

python - 优化目标必须是链接

python - on_delete ='CASCADE' 好像没有效果

python - 我有一个巨大的 If 语句列表,想清理我的代码

Python3 - 将相似的字符串组合在一起

python-3.x - 类型错误 : compile() missing 1 required positional argument: 'self'

python - 用于去除 C 标识符周围的(双)下划线的正则表达式

python - 导入错误 : No module called magic yet python-magic is installed

python - Pandas DF NotImplementedError : Writing to Excel with MultiIndex columns and no index ('index' =False) is not yet implemented

python - 我的 python 正在从另一个文件调用另一个函数而不显式导入它