[英]Meet import error in terminal, but PyCharm can run it
My python project is like this:我的 python 项目是这样的:
- project
|
-- datasets
|
----__init__.py
|
----toy.py
|
--trainer
|
----train.py
In datasets/__init__.py
:在datasets/__init__.py
:
# datasets/__init__.py
from .toy import xxx
And I try to import functions and classes from toy.py
in train.py
.我尝试从toy.py
中的train.py
导入函数和类。 So, in train.py
, I write:因此,在train.py
中,我写道:
import datasets
if __name__ == '__main__':
print(datasets.__dict__)
When I issue python trainer/train.py
in terminal, an import error occurs:当我在终端发出python trainer/train.py
时,出现导入错误:
"ModuleNotFoundError: No module named 'datasets'" “ModuleNotFoundError:没有名为‘数据集’的模块”
But, I can run train.py
in Pycharm by clicking the "run" button on the right corner.但是,我可以通过单击右上角的“运行”按钮在 Pycharm 中运行train.py
。
Can anyone tell me why and give any advice to fix it?谁能告诉我为什么并给出任何建议来解决它?
pycharm adds your project directory to the PYTHONPATH environment variable (you could add other folders with Settings->Project Structure->Add Content Root). pycharm 将您的项目目录添加到 PYTHONPATH 环境变量中(您可以使用 Settings->Project Structure->Add Content Root 添加其他文件夹)。
Outside of the virtual environment of pycharm your project was not set to any search path.在 pycharm 的虚拟环境之外,您的项目未设置为任何搜索路径。 Two options:两种选择:
import sys
sys.path.append(r"../project")
before import datasets
in train.py在 train.py 中import datasets
之前
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.