简体   繁体   中英

Meet import error in terminal, but PyCharm can run it

My python project is like this:

- project
|
-- datasets
|
----__init__.py
|
----toy.py
|
--trainer
|
----train.py

In datasets/__init__.py :

# datasets/__init__.py
from .toy import xxx

And I try to import functions and classes from toy.py in train.py . So, in train.py , I write:

import datasets

if __name__ == '__main__':
    print(datasets.__dict__)

When I issue python trainer/train.py in terminal, an import error occurs:

"ModuleNotFoundError: No module named 'datasets'"

But, I can run train.py in Pycharm by clicking the "run" button on the right corner.

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).

Outside of the virtual environment of pycharm your project was not set to any search path. Two options:

  1. Append project path to PYTHONPATH environment variable (either create new environment variable PYTHONPATH or add path with ";" to existing variable)
  2. use sys.path.append: add following lines
  import sys
  sys.path.append(r"../project")

before import datasets in train.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM