"ImportError: No module named..." when importing my own module

"ImportError: No module named..." when importing my own module

我正在尝试导入模块,但一直收到 ImportError。

在 PortfolioStatus.py 文件中,我有以下代码从 share_data.py 模块导入 share_data class
from Shares.share_data import share_data

我收到以下错误:

File "/home/lucasamos/FYP/Shares/Communication/PortfolioStatus.py", line 3, in <module>
from Shares.share_data import share_data
ImportError: No module named Shares.share_data

为了让事情变得更加混乱,这在我的本地机器上运行良好,但我在 PythonAnywhere 上托管,这就是我收到错误的地方

我的文件层次如下图所示

提前致谢!

你应该试试这个:

import sys
sys.path.append("../Shares/templates")
import share_data

它将您的模板文件夹添加到路径列表中python正在检查模块。

这可能是因为您的 Shares 目录不在您的 PYTHONPATH 中。

请参阅这篇关于使用 PYTHONPATH 的文章: https://users-cs.au.dk/chili/PBI/pythonpath.html

摘录:

Often however, you will need to import a module not located in the same directory as the main program. Continuing the example above, assume you're writing a program located in ~/PBI/ which needs to include mymodule.py.

In order for the Python interpreter to find your module, you need to tell it where to look. You can do that by setting the environment variable PYTHONPATH. Depending on the shell program you use (e.g., xterm), this is done in one of two ways.

Bash:

export PYTHONPATH=${PYTHONPATH}:/users/[your username]/PBI/Modules/

manage.py 文件的一层添加空 __init__.py

这样包含 __init__.py 文件向 Python 解释器表明该目录应被视为 Python 包。

好的,所以我终于解决了。 如一些答案所示,我需要将根文件夹添加到系统路径。

最后我是这样做的:

import sys
sys.path.append("/home/lucasamos/FYP")