'Problem with virtual env: can't import installed packages in the virtualenv

I am doing some tests with virtualenv to see how it works and I think I ran into some trouble.

First I created a folder and changed my path to it:

$ mkdir new_folder 
$ cd new_folder 

Then I created a virtualenv and activated it:

$ virtualenv my_first_venv
$ source my_first_venv/bin/activate

I installed only one package to make a test:

$ pip3 install wget

And I confirmed it was installed indeed:

(my_first_venv)    #this just shows up when you activate it
$pip list

Package    Version
------------------
pip        20.0.2
setuptools 41.2.0
wget       3.2

But if I create a .py file in that same path, and I write "import wget" and run it, I get an error message stating that there is no such module.

Does anyone have an idea of how to fix this?



Solution 1:[1]

It seems that you are running your Python code on global environment, instead of virtual environment which is my_first_venv. One way to do is to run your code using command prompt, after you have activate the virtual environment.

On Windows, script mode:

python <filename.py>

You can also run it in interactive mode, directly prompted a Python shell:

python -i <filename.py>

Solution 2:[2]

After activating your virtual environment, try installing it with this instead:

python -m pip install wget

or try using pip install wget

I'm guessing it's something to do with different pip versions talking to python outside your virtual environment. Let me know how it goes!

Solution 3:[3]

Try installing/importing a package from the system terminal (outside of the IDE/Text editor) using the same interpreter/environment.

Solution 4:[4]

Pay attention to do not have an alias for your python/pip command: an alias overlaps the venv commands. For instance, if you have an alias such as python=python3, then even if you are in your venv, the python command will execute the python alias command (in this example the python3 in your global environment) and not the python venv command.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tomy Tjandra
Solution 2 Davis Engeler
Solution 3 pasindu
Solution 4 Mouti