Code runs in PyCharm, ModuleNotFoundError from the terminal

It's not the first time I encounter this weird unexplained phenomenon of being unable to recognize packages in the terminal and being recognized in PyCharm and vice versa.

I have a directory that looks like this:

ticklab
├── __init__.py
├── extractors
│   ├── __init__.py
│   ├── base_extractor.py
│   ├── extract.py
│   ├── polygon_cli.py
│   ├── polygon_extractor.py
│   └── stocks_debug.txt
└── logs
    └── extraction_session.log

in polygon_extractor.py I need to import BaseExtractor from base_extractor, so I do:

from extractors.base_extractor import BaseExtractor

it runs perfectly fine in PyCharm however when I do this in extractors directory

emadboctor@MacBook-Pro extractors % python3 polygon_extractor.py 

Traceback (most recent call last):
  File "polygon_extractor.py", line 1, in <module>
    from extractors.base_extractor import BaseExtractor
ModuleNotFoundError: No module named 'extractors'

So I added this under main guard and run from PyCharm

print(os.getcwd())

Output:

/Users/emadboctor/Desktop/Code/ticklab

So I tried this from the terminal:

emadboctor@MacBook-Pro ticklab % python3 extractors/polygon_extractor.py 
Traceback (most recent call last):
  File "extractors/polygon_extractor.py", line 1, in <module>
    from extractors.base_extractor import BaseExtractor
ModuleNotFoundError: No module named 'extractors'
emadboctor@MacBook-Pro ticklab % 

There is a solution to the problem by changing the import statement to:

from base_extractor import BaseExtractor

It runs in both PyCharm and terminal but PyCharm code inspection cannot resolve base_extractor

inspection

When I change the import statement to:

from .base_extractor import BaseExtractor

It resolves and runs fine in PyCharm but gives the following error in terminal:

Traceback (most recent call last):
  File "polygon_extractor.py", line 1, in <module>
    from .base_extractor import BaseExtractor
ImportError: attempted relative import with no known parent package

Another solution is adding sys.path.append('..') but is also an unclean solution to the problem.

2 answers

  • answered 2020-09-14 05:17 suresh

    Use below code before importing the extractors import os CURRENT_PATH = os.path.dirname(os.path.abspath(file)) os.chdir(CURRENT_PATH)

  • answered 2020-09-14 08:19 khari-sing

    try adding path /Users/emadboctor/Desktop/Code/ticklab as your PYTHONPATH environmental variable. You can use following command:

    export PYTHONPATH=/Users/emadboctor/Desktop/Code/ticklab