When building a Python project, it’s good to sandbox your project so as to isolate the dependencies of the modules used.
Here we will be using venv to create the virtual environment in Linux. Do note that venv is only available in Python 3.3 and onwards.
1) Open terminal and navigate to the project folder.
Mine is py_nlp, for my Python NLP projects.
You can use ~ symbol if the project folder is in user home folder else you can key the whole path.
$ cd ~/py_nlp
$ cd /home/pi/py_nlp
2. Create the virtual environment folder
We are using venv module which is only available from Python 3.3 onwards.
Now you are inside your project folder, key the following in terminal:
$ python3 -m venv venv
The top command means, using Py3 and module venv, create a venv folder for the virtual environment. You can use other name for the virtual environment but it’s a common practice to use venv (same name as module) for the folder name.
You can see that a folder, name venv, was created inside your project folder. And inside this venv folder, there are other folders, particularly ‘bin’ folder, which contains python interpreter files, pip files and some other files. Next we will call the ‘activate’ file (inside the bin folder), from the terminal to activate the virtual environment. You need to activate the virtual environment in order to use it.
3. Activate and deactivate the virtual environment(VE)
To develope within the VE, you need to activate it. Navigate to your project folder and In the terminal, key the following:
$ source venv/bin/activate
You will notice that your next line starts with ‘(venv)’, which means you are in the VE.
To deactivate or get out of the VE, just type :
(venv)…… $ deactivate
The (venv) disappear, which means you are out of VE. See below pic for the terminal screenshot.
The folders created within venv:
To add a module to the VE, like in this case I would like to add the nltk module to my NLP project, key ‘pip install nltk’. Remember you have to be inside the virtual environment (VE).
(venv) pi@raspberrypi:~/py_nlp $ pip install nltk