英文:
access function from a different subfolder in python project
问题
我有一个Python项目,具有以下结构:
project_folder/
init.py
subfolder/
init.py
main.py
generate_values.py
lib/
init.py
external.py
我正在运行subfolder/main.py
,它在内部调用generate_values.py
。
在generate_values.py
中,我正在调用来自lib/external.py
的函数calculate_external
。
原始代码如下:
from lib.external import calculate_external
当main和generate_values.py文件不在子文件夹中时,这是有效的。
但现在我收到错误消息:
ModuleNotFoundError: No module named 'lib'
经过一些研究,我尝试了以下方法,但仍然收到错误:
from project_folder.lib.external import calculate_external
-->
ModuleNotFoundError: No module named 'project_folder'
from ..lib.external import calculate_external
-->
ImportError: attempted relative import with no known parent package
帮助解决此问题将会很棒。
请注意,main和generate_values必须保留在子文件夹中,因为将有不同的这种子文件夹执行不同的操作,但都使用lib文件夹。
英文:
I have a python project with the following structure:
project_folder/
__init__.py
subfolder/
__init__.py
main.py
generate_values.py
lib/
__init__.py
external.py
where I am running subfolder/main.py
, and it internally calls generate_values.py
.<br>
Inside generate_values.py
I am calling the function calculate_external from lib/external.py
.
The original code was:
from lib.external import calculate_external
<br>
this was working when the main and generate_values py files were not in a subfolder.
but now I get the error
ModuleNotFoundError: No module named 'lib'
after some research i tried the following but still got errors:
from project_folder.lib.external import calculate_external
--><br>
ModuleNotFoundError: No module named 'project_folder'
from ..lib.external import calculate_external
--><br>
ImportError: attempted relative import with no known parent package
Any help in resolving this would be great. <br>
Note that the main and generate_values must stay in a subfolder, because there will be different such subfolders that do different things but all use the lib folder.
答案1
得分: 1
感谢[@Jason Chia](https://stackoverflow.com/users/12085772/jason-chia)和[@Wonka](https://stackoverflow.com/users/5226792/wonka),这是一个可行的解决方案:
在generate_values.py文件中执行:
```python
import sys
sys.path.append("project_folder")
from lib.external import calculate_external
<details>
<summary>英文:</summary>
thanks to [@Jason Chia](https://stackoverflow.com/users/12085772/jason-chia) and [@Wonka](https://stackoverflow.com/users/5226792/wonka) this is a working solution:
in the generate_values.py file do:
import sys
sys.path.append("project_folder")
from lib.external import calculate_external
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论