ModuleNotFoundError – Module found in PyCharm intellisense but not when executing program

Question:

Using PyCharm, I have a project for an SMTP parser with the following structure:

- SMTP
  - Classes
    - Models
    - Transformers
  - Tests 

In Tests I reference classes from SMTP.Classes.Transformers like this:

from SMTP.Classes.Transformers.myclass import MyClass

This works and my unit tests are run properly.

However, I now added a proxy file myProxy.py:

- SMTP
  - Classes
    - Models
    - Transformers
  - Tests 
  - myProxy.py

In myProxy.py I try to import my classes, just like above:

from SMTP.Classes.Transformers.myclass import MyClass

When I type from S, PyCharm actually suggests SMTP and when I write it out, it shows no errors. I can even start myProxy within PyCharm, using the "run" button.

However, when I try to run myProxy.py from console, I get ModuleNotFoundError: No module named 'SMTP'

When I remove the SMTP part from every affected file, then I can run this from console. And it even runs on PyCharm. However, PyCharm does underline my imports as false for some reason.

What exactly is the error here, and how do I solve it so that I don’t have errors in PyCharm and can run my program on both PyCharm and console?

Asked By: Benjamin Basmaci

||

Answers:

You can attempt to omit the SMTP and instead simply mark Classes as Sources Root in PyCharm, by going: right-click on Classes directory > Mark Directory as > Sources Root.

Answered By: tainn