Issue
I know there are dozens of Python package import questions, but I can't seem to find an answer that works. Most answers seem to be about the missing __init__.py to make a package, but I've got one in the base of the project (and I've tried in the sub-folders as well).
I have a project of the form
package
+-- __init__.py
+-- weasel.py
+-- badgers
| +-- __init__.py
| +-- a.py
where weasel.py just contains a test function
def test_function():
return "HELLO"
and I want to be able to call test_function from a.py, I've attempted (all with and without the init.py in the folder badgers) and none of which seem to work.
import weasel -> ModuleNotFoundError: No module named 'weasel'
from . import weasel -> ImportError: attempted relative import with no known parent package
import package.weasel -> ModuleNotFoundError: No module named 'package'
from package import weasel
The hack I've managed to employ thus far, which works fine in Spyder and in my production environment; project is a Dash App (so Flask) deployed to render.
import sys
sys.path.append("..")
import weasel
But this just throws ModuleNotFoundError in VS Code.
I'm not adverse to a hack :S but the needs of the current project kinda make life much, much, easier if I could build the project in VS Code.
Please, I implore the stackoverflow community could someone please let me know what I'm doing wrong? Or a hack that will work in VS Code?
Thank you,
Solution
This is caused by the path. The path of vscode running file is not the current file path. You need to add it manually.
import sys
sys.path.append("your package's Path") #for example, my path is "C:/my_python/package"
import weasel
Here is my directory structure.
Tips:
Do not use "..", it will really adds two commas to path instead of parent directory.
Answered By - MingJie-MSFT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.