Creating and managing Python virtual environments
code/ --- hello.py
and the content of our
import os import numpy as np print(os.listdir())
hello.pyfile. Now, let's create a Python virtual environment of name
myVirtualEnvto run our
python3 -m venv myVirtualEnv/
After this, the project directory tree will look like
code/ --- hello.py --- myVirtualEnv/
hello.pyneeds to import numpy.
# activate the virtual environment source myVirutalEnv/bin/activate
Now you should be in your virtual environment. Let’s install the numpy.
# install numpy pip install numpy
After this, we can run our
hello.py script and see the output.
# run the hello.py script puthon3 hello.py
Next to deactivate the virtual environment just run this command.
# do this with the virtual environment activated. pip freeze > requirements.txt
# the numpy version number will be different numpy==numpy_version_number
code/ --- hello.py --- requirements.txt
requirements.txtfile like this.
# with the virtual environment activated pip install -r requirements.txt
hello.pyscript without doing anything else. Isn't that neat
Automating the whole process
setup.shwill look like this
#!bin/sh # create the virtual environment named myvenv python3 -m venv myvenv/ # activate the virtual environment source myvenv/bin/activate # install the necessary packages pip install -r requirements.txt # run the python script python3 hello.py # deactivate the virtual environment deactivate # delete the virtual environment rm -r myvenv
To run the script do this
Here, I have assumed that you have Python 3 installed and your operating system is some variant of Linux. Similar can be acheived on MAC OS or Windows.
Anaconda is a popular package manager for Python and other programming languages. In the next post, we will learn how we can achieve the process described above using Anaconda virtual environments. Cheers