Issue
I have created a python script inside the virtualenv and tried to execute that file. This is my code:
(env) C:\Users\amitayadav\Documents\Amita_projects\Python\flask_project>python3 app.py
Traceback (most recent call last):
File "app.py", line 1, in <module>
from flask import Flask
ModuleNotFoundError: No module named 'flask'
It throws an error. However, when I run this command it runs fine:
(env) C:\Users\amitayadav\Documents\Amita_projects\Python\flask_project>python app.py
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 500-586-454
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
I don't understand why this is happening. What is the problem with the python3 command?
Solution
The packages are installed only for the Python version that the virtual environment is configured to use, which is generally just run as python
.
When the virtual environment is created, the interpreter is copied for use within that environment. By running the python3
interpreter, you might end up with an interpreter outside your environment, that doesn't have the required dependencies installed.
If you want to have the virtual environment use the Python 3 version, you might need to create the virtualenv with the optional --python
flag to indicate that:
virtualenv --python=python3 my_virtual_env_directory
Then you just again install the required packages as before:
pip install flask
Then you just run as usual:
$ python
Python 3.6.7 (default, Oct 29 2018, 11:42:59)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import flask
>>>
The correct versions of pip
and the interpreter python
are used implicitly to install dependencies and to run your application.
Answered By - moooeeeep Answer Checked By - David Marino (WPSolving Volunteer)