问题描述
我有一个具有以下结构的软件包:
I have a package with the following structure:
model\
__init__.py (from model.main_trainer import *, etc.)
main_trainer.py
snn.py
splitter.py
main_trainer.py脚本至少接受三个参数作为输入:
The main_trainer.py script takes at least three arguments as inputs:
#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)
但是,如果我在终端中运行以下内容:
However, if I run in the terminal the following:
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'
另一方面,如果我这样使用相对路径:
On the other hand, if I use the relative path as such:
# 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
我也尝试过将其运行为:
I have also tried running it as:
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:__main__不是软件包是什么意思? , Python 3中的相对导入
I have checked these posts to no avail:ModuleNotFoundError: What does it mean __main__ is not a package?,Relative imports in Python 3
推荐答案
在脚本/模块路径上添加sys
模块,然后导入子模块.
Append your script/module path with sys
module then import your sub modules.
sys.path.append('/path/to/your/model/modules/')
希望这可以解决您的问题.
Hope this will solve your problem.
修改了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 *
这篇关于ModuleNotFoundError:没有名为“模型"的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!