在不修改 sys.path 的情况下无法从根目录导入到子目录(Python 3.8)
我尝试过的
首先我要说的是,我已经阅读了大约 5 或 6 个与此相关的其他 stackoverflow 问题,并且已经对此进行了很多讨论。这是我发现和尝试的内容:
“在其他导入之前执行
sys.path.append(
。”) 问题:这可行,但违反了 PEP 标准实践,因此我宁愿找到一个不需要修改
sys.path
的解决方案。“使用
imp
库查找您的模块。”问题:该答案中概述的解决方案已被弃用,因为
importlib
是新的imp
,我不确定如何使用importlib
即使在查看文档之后也是如此。“在根目录中添加一个空的
__init__.py
文件。”问题:这不起作用。
我的问题的详细信息
这是我的文件结构:(
Project/
├ subdir/
| └ script.py
├ __init__.py
└ module.py
请注意,我将空的 __init__.py
文件留在那里,以防需要。)
我正在尝试从 module.py 导入
到 subdir/script.py
:
module.py
的内容:
def func():
print('func was called')
subdir/script.py
的内容:
from module import func
func()
但是,当我在终端中运行 python3 script.py (在 Mac 上),我收到此错误消息:
Traceback (most recent call last):
File "script.py", line 1, in <module>
from module import func
ModuleNotFoundError: No module named 'module'
我希望有一个不需要修改 sys.path 的简单解决方案。
What I have tried
First let me say, I have read maybe 5 or 6 other stackoverflow questions related to this and many things have been said about this. Here's what I found and what I tried:
"Do
sys.path.append(<root dir>)
before other imports."Issue: This works, but it's against PEP standard practice so I'd rather find a solution that does not require modifying
sys.path
."Use the
imp
library to find your module."Issue: The solution outlined in that answer is deprecated as
importlib
is the newimp
, and I'm not sure how to useimportlib
even after looking at the docs."Add an empty
__init__.py
file in your root directory."Issue: This does not work.
Details of my problem
Here is my file structure:
Project/
├ subdir/
| └ script.py
├ __init__.py
└ module.py
(Note that I left the empty __init__.py
file in there just in case it's needed.)
I'm trying to import from module.py
to subdir/script.py
:
Contents of module.py
:
def func():
print('func was called')
Contents of subdir/script.py
:
from module import func
func()
However, when I run python3 script.py
in terminal (on Mac), I get this error message:
Traceback (most recent call last):
File "script.py", line 1, in <module>
from module import func
ModuleNotFoundError: No module named 'module'
I would appreciate a straightforward solution that does not require modifying sys.path
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决您的问题的最简单方法可能是重组您的项目:
Probably the easiest way to solve your problem is to restructure your project:
我通过设置 PYTHONPATH 解决了我的问题。就我而言,它适用于此。
I solved my issue by setting
PYTHONPATH
. In my case, it works with this.