ModuleNotFound error in cmd but pip works

Viewed 24

i recently rescountred this problem: i can't run python apps with modules in cmd. I can install modules with pip (it works perfectly), i can run an python code, but if i use a module (installed with pip) it doesn't work with 'ModuleNotFound' error. But if I execute the code from Idle or Pycharm it works fine. How can I solve this issue?

1 Answers

If you have a folder other than the ones you've created( called venv or something like that) then you have a virtual environement installed in your project.
Before running your code you need to activate that virtual environement by going to the directory that contains your python project and running this command:

name-of-virtual-environement\scripts\activate

The name of your virtual environement is the name of that folder so if it's venv you need to run the command

venv\scripts\activate

By default, pycharm creates virtual environements for your projects that's why whenever you create a new project and you import a module that you already used before in another project you need to install it again because that module was only installed in the virtual environement of that project and not globally.
If you never used virtual environements you might wonder why we need them. In fact, they are very useful in avoiding versions mismatch. For example if you worked in a project using Pandas version 1.3 and you installed it globally then you create a new project in which you need to use Pandas version 1.4 in that case pandas 1.3 will be removed and version 1.4 will be installed so if you try to run the first project again pandas 1.4 which can cause trouble sometimes.

Related