问题
I have a package with the following structure:
model\
__init__.py (from model.main_trainer import *, etc.)
main_trainer.py
snn.py
splitter.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'
I get the following error:
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 *
I get this error:
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 ...
and then I get this error:
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
I have checked these posts to no avail: ModuleNotFoundError: What does it mean __main__ is not a package?, Relative imports in Python 3
回答1:
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.
Edit:
Modified your main_trainer
file
#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 *
来源:https://stackoverflow.com/questions/62365432/modulenotfounderror-no-module-named-model