[英]Importing from parent directory python
I have the following structure:我有以下结构:
app/
code/
script.py -- has a function called func
main.py
How can I import script.py
from main.py
?如何从
main.py
导入script.py
?
I tried from code.script import func
and I got ModuleNotFoundError: No module named 'code.script'; 'code' is not a package
我尝试
from code.script import func
并得到ModuleNotFoundError: No module named 'code.script'; 'code' is not a package
ModuleNotFoundError: No module named 'code.script'; 'code' is not a package
Place a __init__.py
file in the code
directory.在
code
目录中放置一个__init__.py
文件。 This will allow your main.py
code to import it as a module like you have tried there.这将允许您的
main.py
代码将其作为模块导入,就像您在那里尝试过的那样。
Indeed the best way is to add __init__.py
in code
directory because when a regular package is imported __init__.py
file is implicitly executed and the objects it defines are bound to names in the package's namespace.实际上,最好的方法是在
code
目录中添加__init__.py
,因为当导入常规 package 时, __init__.py
init__.py 文件会被隐式执行,并且它定义的对象绑定到包命名空间中的名称。
FYI, as an alternative you can also to this in your main.py
before the import:仅供参考,作为替代方案,您也可以在导入之前在
main.py
中对此进行替换:
import sys
sys.path.append("/path/to/script.py")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.