Python 相对路径 - ModuleNotFoundError

Python Relative Path - ModuleNotFoundError

我需要 pickle python class 我已经实例化了,因此需要使用相对路径。我正在使用 Python 版本 3.6.6。以下是项目结构和代码的示例:

modelling/
    test.py
    mod1/
        __init__.py
        classic_mod.py

init.py

from .classic_mod import classic

classic_mod.py

class classic:

    def __init__(self, input_string):
        self.input_string = input_string
        print(self.input_string)

    def log_info(self):
        print(self.input_string)

test.py

from .mod1 import classic_mod
from sklearn.externals import joblib

model = classic_mod.classic("Hello World!")
joblib.dump(model, "model.pkl")

如果我使用绝对路径,当我将 pickle 文件加载到另一个文件夹的 python 时,我会遇到问题。当我 运行 test.py 我收到一条错误消息:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    from .mod1 import classic_mod
ModuleNotFoundError: No module named '__main__.mod1'; '__main__' is not a package

如何解决这个导入错误,同时 pickle class 以便我可以在其他地方使用?

您需要将代码封装在一个包中才能使用相对导入。 Set a setup script and use the pip -e install flag to install it as a development module. This 很好的深入解释了你所面临的问题。