从Python项目的不同子文件夹中访问函数

huangapple go评论65阅读模式
英文:

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'

经过一些研究,我尝试了以下方法,但仍然收到错误:

  1. from project_folder.lib.external import calculate_external -->
ModuleNotFoundError: No module named 'project_folder'
  1. 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 &#39;lib&#39;

after some research i tried the following but still got errors:

  1. from project_folder.lib.external import calculate_external --><br>
    ModuleNotFoundError: No module named &#39;project_folder&#39;
  2. 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>



huangapple
  • 本文由 发表于 2023年7月17日 17:03:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定