简体   繁体   中英

Python 3.6.1 does not find package and module [import]

I am starting a Python project, and I have structured my code in packages and sub-packages in the following way:

FCM
|-- definitions
|   |-- Classifiers
|   |-- __init__.py
|   `-- triggers
|       |-- __init__.py
|       |-- probability.py
|-- examples
|   |-- __init__.py
|   |-- compute
|   `-- study
`-- source
    |-- __init__.py
    |-- FastComposedModels_pb2.py
    |-- genetic_algorithm
    `-- trigger_evaluator.py

Module imports between sub-packages work, however when I try to import the triggers subpackage from inside./examples or./source:

import definitions.triggers

I get this error:

ModuleNotFoundError: No module named 'definitions.triggers'

Here's the sys.path variable value:

/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages
/home/projects/FCM
/apps/PYTHON/3.6.1/INTEL/lib/python36.zip
/apps/PYTHON/3.6.1/INTEL/lib/python3.6
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/lib-dynload
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages/pytz-2017.2-py3.6.egg
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages/packaging-16.8-py3.6.egg
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages/appdirs-1.4.3-py3.6.egg
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages/cycler-0.10.0-py3.6.egg
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages/nose-1.3.7-py3.6.e

I am using Python 3.6.1 in Linux, however, this does not happen to me in any other platform and python version. I do not understand why I can't find the triggers sub-package. Do I miss something?

It seems that there was already a "definitions" module in my python version.

Below are the steps I followed. First I imported the definitions module. Then I printed the modules loaded. And finally, I realized that the path to the package/module was not consistent to where my project was located.

import definitions
import sys
print('\n'.join(sys.modules))

It outputs:

...
source.genetic_algorithm
definitions

Then you can get the location of the module by doing:

print(sys.modules['definitions'])

You're trying to do a relative import, which requires a leading period ('.') character. Try

from .definitions.triggers import <function>

More details at The Python Import System docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM