ModuleNotFoundError:没有名为“模型”的模块

时间:2020-06-13 20:54:18

标签: python import module package python-import

我有一个具有以下结构的软件包:

model\
    __init__.py (from model.main_trainer import *, etc.)
    main_trainer.py
    snn.py
    splitter.py

main_trainer.py脚本至少接受三个参数作为输入:

#main_trainer.py

import numpy as np # Linear algebra
import pandas as pd # Data wrangling
import re # Regular expressions

import matplotlib


# Avoid plotting graphs
matplotlib.use('Agg')

# Custom dependencies
from model.snn import *
from model.splitter import *

def main_trainer(dataset_name, model_dict = None, train_dict = None,
                 how = 'k-fold cross-validation', save = True):
    etc.

if __name__ == '__main__':
    dataset_name, model_dict, train_dict, how = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
    main_trainer(dataset_name, model_dict, train_dict, how)

但是,如果我在终端中运行以下内容:

python main_trainer.py dataset_name model_dict train_dict 'k-fold cross-validation'

我收到以下错误:

Traceback (most recent call last):
  File "main_trainer.py", line 17, in <module>
    from model.snn import *
ModuleNotFoundError: No module named 'model'

另一方面,如果我这样使用相对路径:

# Custom dependencies
from .snn import *
from .splitter import *

我收到此错误:

Traceback (most recent call last):
  File "main_trainer.py", line 17, in <module>
    from .snn import *
ModuleNotFoundError: No module named '__main__.snn'; '__main__' is not a package

我也尝试过将其运行为:

python -m main_trainer ...

然后出现此错误:

Traceback (most recent call last):
  File "/home/kdqm927/miniconda3/envs/siamese/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/kdqm927/miniconda3/envs/siamese/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/projects/cc/kdqm927/PythonNotebooks/model/main_trainer.py", line 17, in <module>
    from .snn import *
ImportError: attempted relative import with no known parent package

我检查了这些帖子无济于事: ModuleNotFoundError: What does it mean __main__ is not a package?Relative imports in Python 3

1 个答案:

答案 0 :(得分:1)

在脚本/模块路径上附加sys模块,然后导入子模块。

sys.path.append('/path/to/your/model/modules/')

希望这可以解决您的问题。

编辑:

修改了您的main_trainer文件

#main_trainer.py

import numpy as np # Linear algebra
import pandas as pd # Data wrangling
import re # Regular expressions
import sys
import matplotlib


# Avoid plotting graphs
matplotlib.use('Agg')

# Custom dependencies
sys.path.append('/projects/cc/kdqm927/PythonNotebooks/model/') #folder which contains model, snn etc.,
from snn import *
from splitter import *