Another situation that comes up often is the need to test a package in a different version of Python. conda makes it easy to create a suitable environment. In this recipe, we will show you how to create and use environments with version 2.7 of Python.
Using conda environments to run different versions of Python
Getting ready
This recipe assumes that you have a working installation of Anaconda. If you don't, follow the recipe for installing Anaconda on your operating system presented previously in this chapter.
How to do it...
- Create the new environment with the following command:
conda create --name python27 python=2.7
conda will display information about the changes and ask for confirmation. Go ahead and enter yes to accept the environment creation.
- To activate the environment on Linux and macOS, use the following command:
source activate python27
- On Windows, the command to activate an environment is as follows:
activate python27
- Let's now test the new environment. Start Python in the usual way after activating the environment. Notice that in the startup message, it should state that version 2.7 of Python is being run. Now run the following statement in the Python prompt:
zip([['a','b'],[1,2]])
- This will produce the following output:
[('a', 1), ('b', 2)]
- This confirms that we are running Python 2, since in Python 3 the zip() function returns an iterator object instead of a list. To leave the Python shell, run the following in the Python prompt:
quit()
- When done with the environment, deactivate it by running the following command on Linux and macOS:
source deactivate python27
- On Windows, run the following:
deactivate python27