[英]Importing python modules from a subfolder
I would like to import modules from within the following folder structure by referencing the sub-module app
.我想通过引用子模块
app
从以下文件夹结构中导入模块。
├── src
│ ├── __init__.py
│ └── app
│ ├── __init__.py
│ ├── getters
│ │ ├── company_1.py
│ │ └── company_2.py
│ ├── parsers
│ │ ├── company_1.py
│ │ └── company_2.py
│ └── writers
│ ├── company_1.py
│ └── company_2.py
Here is an example of what I want to do:这是我想要做的一个例子:
# src/app/writers/company_1.py
import app.parsers.company_1 as parser_1
def write_data(event, context):
...
but I get the error ModuleNotFoundError: No module named 'app'
.但我收到错误
ModuleNotFoundError: No module named 'app'
。 I don't understand why this shouldn't work.我不明白为什么这不起作用。
NOTE笔记
Why am I including the seemingly redundant sub-folder app
?为什么我要包含看似多余的子文件夹
app
? The side story here is that the functions writers/company_*.py
will be implemented as Lambda functions on AWS, and in order to get all the necessary dependencies, I need to upload the contents of the src folder to AWS but need to have a top-level folder with a known name so that I can use it for absolute imports.这里的附带故事是,函数
writers/company_*.py
将在 AWS 上实现为 Lambda 函数,为了获得所有必要的依赖项,我需要将 src 文件夹的内容上传到 AWS,但需要有一个具有已知名称的顶级文件夹,以便我可以将其用于绝对导入。 Without app
the contents of src are uploaded to a folder with an autogenerated name which I cannot reference.如果没有
app
,src 的内容将上传到一个我无法引用的自动生成名称的文件夹中。
I first tried relative imports, but received an attempted relative import with no known parent package
error, so now I am going for absolute imports, inspo from here .我首先尝试了相对导入,但收到了一个
attempted relative import with no known parent package
错误,所以现在我要进行绝对导入,从这里开始。
You can add this in the code ,你可以在代码中添加这个,
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "source"))
Just replace source
with the folder where you have saved your modules.只需将
source
替换为您保存模块的文件夹。 In this case replace source
with app
在这种情况下,用
app
替换source
Did you try having in __init__.py
inside your app folder ?您是否尝试将
__init__.py
放在您的应用程序文件夹中?
module
|
|--module
| |
| |--__init__.py
| |--module.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.