Python软件包导入在Spyder中起作用,但与代码无效
我知道有数十个Python软件包导入问题,但我似乎找不到有效的答案。大多数答案似乎是关于丢失的__init__.py来制作一个包裹,但是我在项目的基础上有一个包裹(并且我也尝试了子文件夹)。
的形式的项目
package
+-- __init__.py
+-- weasel.py
+-- badgers
| +-- __init__.py
| +-- a.py
我有一个weasel.py只包含测试功能
def test_function():
return "HELLO"
,我希望能够从a.py调用test_function,我已经尝试过(全部带有和不带有 init .py .py。在文件夹badge中),似乎没有用。
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
到目前为止,我设法采用的黑客攻击在Spyder和我的生产环境中都很好。项目是部署的仪表板应用程序(SO烧瓶)。
import sys
sys.path.append("..")
import weasel
但这只是在VS代码中抛出ModulenotFoundError。
我对hack:s并不不利,但是如果我可以用VS代码构建项目,那么当前项目的需求会变得更加轻松。
拜托,我恳求stackoverflow社区有人可以让我知道我在做什么错吗?还是将在VS代码中起作用的黑客?
谢谢你,
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,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是由路径引起的。 VSCODE运行文件的路径不是当前文件路径。您需要手动添加它。
这是我的目录结构。
提示:
不使用” ..“它确实会将两个逗号添加到路径上,而不是父级目录。
This is caused by the path. The path of vscode running file is not the current file path. You need to add it manually.
Here is my directory structure.
Tips:
Do not use "..", it will really adds two commas to path instead of parent directory.