Conda for virtual environments

In many cases, it is beneficial to be able to switch between different versions of Python – for testing purposes, or if some specific package or tool does not support the version you normally use. Moreover, in some cases, it might be nice to switch between different sets of installed packages (or different versions of the same ones), again for the purpose of testing, or if they somehow conflict with one another. You can easily do both things using Conda environments. 

Compared to virtual machines, environments do not allocate resources, memory or CPU, but merely substitute paths to specific tools – in our case, Python, and install packages, temporarily, tricking a machine into running different versions as if they were just swapped. In fact, you were using one Conda environment – root – all this time! Even if you're not going to run tests, it is a very good idea to create a separate environment for your work. Sooner or later, you will accidentally break your environment by either installing something bad or in another way. If this is a secondary environment, you can simply remove it, and then recreate it within 5 minutes. As a bonus, we can declare all the packages required for the specific project in a text file and share it with others, so that they can create an identical environment for their work.

In order to create a new environment, just type the following:

conda create -n myenv python=3.7 jupyter scikit-learn

In this code, myenv is the name of your new environment, and everything after this is the base packages you want to install there – don't worry, those are optional, and the list doesn't need to be complete.

Now, in order to start working in the environment, type conda activate myenv – you'll notice that the start of the line will change. Now, anything that you install using Conda, or PIP (Python's original package manager) will be installed in that environment – and every Python operation will use the corresponding Python version. You can always exit the environment by typing conda deactivate.

Now, by way of example, let's install pandas via conda install pandas and pretend that the resulting environment is the final version we want to store, in order to recreate it later, ourselves, or share it with colleagues. It's simple! Just type the following:

conda env export > environment.yml

This will generate and store specifications for the currently active Conda environment as a YAML file. You can edit this file, by adding and removing packages, store it in Git, share it with anyone, and so on. Once you want to use it, write the following:

conda env create -f environment.yml

You can further specify the preferred name of the environment, overriding the naming from the file itself.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.195.128