将内部模块导入Python的另一个子目录的最佳实践是什么?
我目前有一个构成此
Project/
main.py
.gitignore
.env
requirements.txt
reports/
report1.py
report2.py
utils/
__init__.py
support_functions.py
程序的项目文件夹,我没有尝试运行主要功能。我有几个报告,每周/一个月一次运行一次,然后直接从文件中运行它们。 我在从Utils模块中导入功能时遇到了很多麻烦 - 但是,我确实在堆栈溢出上找到了解决方法,这实际上是将文件夹添加到路径中,
import sys
sys.path.append('/Project/utils')
import support_functions
但是,我不喜欢此解决方法,因为它使用了绝对路径,当我切换计算机/OS/Enviroments时,将行不通。 因此,我的主要问题是如何处理大型项目?即使我使用“正确”结构并运行主函数,我也遇到了其他几个方案,即使我想这样做。
- 一个测试文件夹,该文件夹将从另一个模块中导入函数,以测试
- 我想从另一个内部模块导入函数或类的任何情况
- 。我是否缺少有关建筑的明显的东西?
I currently have a project folder structured as this
Project/
main.py
.gitignore
.env
requirements.txt
reports/
report1.py
report2.py
utils/
__init__.py
support_functions.py
For this program, I am not trying to run a main function. I have several reports that I run once a week/month, and just run them straight from its file.
I was having a lot of trouble importing the functions from the utils module - however, I did find a workaround on stack overflow which is essentially adding the folder to the path
import sys
sys.path.append('/Project/utils')
import support_functions
However, I don't love this workaround as it uses an absolute path, and wouldn't work when I am switching computers/os/enviroments.
So my main question is how is this handled on larger projects? I have run into a couple other scenarios where I want to do this, even when I am using the "correct" structure and running a main function.
- A test folder, which would import functions from another module for testing
- Any situation when I want to import a function or class from another internal module
- Is this just not commonly done in python? Am I missing something obvious regarding architecture?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我终于找到了答案。
解决方案:用注释-JSON编辑您的设置
-OSX需要更改为这些操作系统上的“ Linux”或“ Windows”。
可以找到有关问题和解决方案的文档在这里 “ 部分。
还有其他解决方案可以通过在.env中设置pythonpath,然后在设置中指向它。解决方案最终将Vscode点放在当前的工作目录中,这是在Pycharm中自动完成的。
I FINALLY found the answer.
Solution: Edit your settings.json with
Note - osx will need to be changed to "linux" or "windows" on those operating systems.
Documentation on the issue and solutions can be found here under the "Use of the PYTHONPATH variable" section.
There are alternative solutions of changing your PYTHONPATH by setting it in your .env, and then pointing to that in settings.json, however, neither worked for me. Solution ended up being to have VScode point the PYTHONPPATH to the current working directory, something that is done automatically in Pycharm.