python - 导入模块时如何解决问题?
问题描述
下面是我的文件夹结构。
My_Project
|
+-- Project
|
+-- file1.py
|
+-- folder1.py
|
+-- folder2.py
|
+--file2.py
谁能帮助我如何将 file2.py 中的 file1.py 作为模块导入?
到目前为止,我已经尝试过使用这样的东西,但它不起作用:
from Project.file1 import some_function which return No module named 'Project'
我也试过:
from ...file1 import some_function
这返回,尝试相对导入,没有父包。
解决方案
I found this answer by Cameron:
By default, you can't. When importing a file, Python only searches the current directory, the directory that the entry-point script is running from, and sys.path which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases).
However, you can add to the Python path at runtime:
# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')
import file
Edit: I later found this answer by joey:
Nothing wrong with:
from application.app.folder.file import func_name
Just make sure folder also contains an init.py, this allows it to be included as a package. Not sure why the other answers talk about PYTHONPATH.
推荐阅读
- c# - 无法使用 VIsual Studio 2019 安装 dotnet-svcutil 来注册 wsdl 服务
- python - 我想在 python rewrite 中编写 discord bot 以检查仅在频道中发送的嵌入中的内容
- python - Python statsmodels 保存的模型文件可以转换为 ONNX Runtime 格式吗?
- sql - 我有日期函数来创建输入日期并创建随机时间我想将它们结合起来
- php - 仅当没有评论时,如何在 wordpress 循环中隐藏评论计数
- typo3 - TYPO3 9/10,tx_form 隐藏标签或添加 css 类
- php - 循环遍历类别 - 显示相关图像和标题
- python - 编写一个函数来获取单行字符串
- r - ggpaired boxplot - 配置轴标题大小、背景等
- ios - 使用 Firebase Firestore 按距离对用户进行排序