![](/img/trans.png)
[英]Can you use relative and absolute imports at the same time with python?
[英]Set python system path to project root directory: can not use absolute imports this way
如果我有一个具有以下结构的项目:
.
├── another_sub_dir
└── sub_dir
├── random_module.py
└── script.py
该项目有两个子目录。 当我使用命令python sub_dir/script.py
script.py 从我的根文件夹运行我的 script.py 并打印sys.path
时,它将sub_dir
打印为路径。 所以Users/me/project/sub_dir
。 当我想在我的script.py
中使用绝对导入路径时( from sub_dir.random_module import random_func
它会抛出一个错误:
from sub_dir.random_module import random_func
ModuleNotFoundError: No module named 'sub_dir'
如何在执行script.py
时将我的项目目录设置为系统路径?
正如我在评论中所说,您想将sub_dir
设置为 package。您可以通过向其中添加一个名为__init__.py
的文件来实现。 你希望你的结构看起来像
.
├── another_sub_dir
└── sub_dir
├── __init__.py
├── random_module.py
└── script.py
然后,您可以从根目录运行python sub_dir/script.py
,它将成功地从sub_dir.random_module
导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.