For example, we have a file with the following structure:
pkg/
__init__.py
libs/
some_lib.py
__init__.py
components/
code.py
__init__.py
if we want to call in
module, such as using relative call: code.py
libs/some_lib.pyfrom.. Libs.some_lib import something
, it is not enough simply to add /___ to the package. Py
. Python returns the error ValueError: first import in non-package
. So how do you solve this problem?
has the following solution:
Add the current path to sys.path
considering that compontent
and libs
are folders at the same level, we can add the following code directly in code.py
to add the parent folder of the current folder to the system path.
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
or the following (this is true for any relational folder, as long as we give the absolute path to the folder in lib_path
) :
import os, sys
lib_path = os.path.abspath(os.path.join('..'))
sys.path.append(lib_path)
so we can import something with from libs.some_lib import something
.
executes the code in package
mode:
python -m pkg.components.code
and then we can use from.. Libs.some_lib import something
to import.
note that you don’t need .py
to end the file.
summary h2>
we can actually combine these two approaches:
if __name__ == '__main__':
if __package__ is None:
import sys
from os import path
sys.path.append( <path to the package> )
from libs.some_lib import something
else:
from ..libs.some_lib import something
div>
Read More:
- Jenkins reported an error modulenotfounderror: no module named filename solution
- Python server run code ModuleNotFoundError Error [How to Solve]
- From in Python__ future__ The role of import *
- Python how does a. Py file call classes and functions in another. Py file
- An import error is reported in the python. The solution to setting. Pylintrc is invalid
- sys.path.append(), os.path.exists(), os.path.join() and os.makedirs() meaning
- ModuleNotFoundError: No module named xxx
- The solution to the error of importing CSV from Python to Python
- Solution: windowserror: [error 2]
- Golang determines whether the directory is empty
- Python uses cxfree to package script files into executable programs
- Python calls DLL and reports an error windowserror: [error 126]
- Visual slam Lesson 6: curve fitting with g2o, error: cmake error at CMakeList.txt (find_ package) By not providing“FindG2O.cmake“
- Fatal Python error: initfsencoding: unable to load the file system codec
- Ctypes loading DLL error oserror: [winerror 126] the specified module could not be found
- Can’t find Python executable “D:\python3\python.exe”, you can set the PYTHON env variable.
- AttributeError: ‘NoneType‘ object has no attribute ‘append‘
- Python error: command error out with exit status 1:
- Running Python 3.7 web.py Runtimeerror: generator raised stopiteration exception occurred during test
- Failed to resolve: com.se renegiant:common 1.5.20