problem in python relative import
I am running the following project on windows with the following directory structure..
Project\Src\Lib\General\Module_lib.py
Project\S开发者_Go百科rc\executables\example.py
Now , I want to import Module_lib.py
in example.py
.. Please help me how to solve this?
content of example.py
:
from ..lib.general.Module_lib import Module_lib
output :
Value Error : Attempted relative import in non-packages
what is the best way to achieve this ?
Add Project\Src\Lib\General
to your PYTHON_PATH so the runtime can find it. That's the only real convenient solution I can think of.
You can find a way of adding your python path here: https://stackoverflow.com/questions/6318156
Doing it in script is also possible:
import sys
sys.path.append(os.path.dirname(__file__))
This won't work out of the box because the dirname
call is to your current file. To fix this you can call it multiple times to move up directories. I hope this is clear enough.
dir1 = os.path.dirname(__file__)
dir1up = os.path.dirname(dir1)
dir1upup = os.path.dirname(dir1up)
You need to define the PYTHONPATH environment variable so that it contains all the directories where you want Python to look for your modules. Assuming that your source tree is in the root of the C: drive you have two options:
Add all the leaf directories to PYTHONPATH and import your modules directly e.g.:
set PYTHONPATH=C:\Project\Src\Lib\General
In this case you can import your module directly:
import Module_lib
Make packages of your directories by adding empty files named
__init__.py
, so that you may use qualified names to import your modules and have less directories to add to your PYTHONPATH. You could do something like:set PYTHONPATH=C:\Project\Src
In this case you can import your module with a suitable qualified name:
import Lib.General.Module_lib
To achieve this you need to add an empty file named
__init__.py
to the C:\Project\Src\Lib and the C:\Project\Src\Lib\General directories.
精彩评论