Create virtual environments for python with conda
A virtual environment is a named, isolated, working copy of Python that that maintains its own files, directories, and paths so that you can work with specific versions of libraries or Python itself without affecting other Python projects. Virtual environmets make it easy to cleanly separate different projects and avoid problems with different dependencies and version requiremetns across components. The conda command is the preferred interface for managing intstallations and virtual environments with the Anaconda Python distribution. If you have a vanilla Python installation or other Python distribution see virtualenv
Outline
- Check conda is installed and available
- Update conda if necessary
- Create a virtual environment
- Activate a virtual environment
- Install additional python packages
- Deactivate a virtual environment
- Delete a virtual environment
Jargon
Requirements
- Anaconda Python distribution installed and accessible
1. Check conda is installed and in your PATH
- Open a terminal client.
- Enter conda -V into the terminal command line and press enter.
- If conda is installed you should see somehting like the following.
2. Check conda is up to date
- In the terminal client enter
- Upadate any packages if necessary by typing y to proceed.
3. Create a virtual environment for your project
- In the terminal client enter the following where yourenvname is the name you want to call your environment, and replace x.x with the Python version you wish to use. (To see a list of available python versions first, type conda search «^python$» and press enter.)
- Press y to proceed. This will install the Python version and all the associated anaconda packaged libraries at “path_to_your_anaconda_location/anaconda/envs/yourenvname”
4. Activate your virtual environment.
- To activate or switch into your virtual environment, simply type the following where yourenvname is the name you gave to your environement at creation.
- Activating a conda environment modifies the PATH and shell variables to point to the specific isolated Python set-up you created. The command prompt will change to indicate which conda environemnt you are currently in by prepending (yourenvname) . To see a list of all your environments, use the command conda info -e .
5. Install additional Python packages to a virtual environment.
- To install additional packages only to your virtual environment, enter the following command where yourenvname is the name of your environemnt, and [package] is the name of the package you wish to install. Failure to specify “-n yourenvname” will install the package to the root Python installation.
6. Deactivate your virtual environment.
- To end a session in the current environment, enter the following. There is no need to specify the envname — which ever is currently active will be deactivated, and the PATH and shell variables will be returned to normal.
6. Delete a no longer needed virtual environment
- To delete a conda environment, enter the following, where yourenvname is the name of the environment you wish to delete.
Related info
The conda offical documentation can be found here.
eResearch cookbook — 2 minute recipes for scientists
- eResearch cookbook — 2 minute recipes for scientists
A template for capturing task recipes for repeatable scientific practices in a consistent format and hosted in a centralised online repository
Managing environments¶
On the Environments page, the left column displays your environments. At the bottom of the environments list are the Create, Clone, Import, Backup, and Remove buttons.

Searching for an environment¶
In the Search Environments box, type all or part of an environment name to filter the environment list.

Creating a new environment¶
At the bottom of the environments list, select Create.
In the Create new environment dialog, type a descriptive name for the new environment.

Select Python or R to set the package type for your environment.
Select a version for your Python or R installation.
Click Create.
Using an environment¶
In the environments list, select the environment name to activate it.
Click the arrow button next to the environment name to open the activation options dropdown.

Select one of the following options for opening the environment: Terminal, Python interpreter, IPython Console, or Jupyter Notebook.
Some of these options may not be available if they were not installed in the environment.
Cloning an environment¶
- Activate the environment you want to clone by selecting it from the environments list.
- At the bottom of the environments list, click Clone.
- Type a descriptive name for the new environment.
- Click Clone.

Backing up an environment¶
Don’t delete your environment backup when removing and reinstalling Anaconda. If you do, you will not be able to import your existing environments into your new installation.
Activate the environment you want to back up by selecting it from the environments list.
At the bottom of the environments list, click Backup.

In the Backup Environment dialog, select either Local drive or Anaconda Nucleus as the backup location. You need to have a Nucleus account to back up your environment to Nucleus.
By backing up to the cloud (Nucleus), your environment is safe from hard drive failure and malfunctions with your machine.
Backing up locally can be useful for rolling back conda to an earlier state feature.
- Click Backup.
- Type a descriptive name for your environment’s YAML file.
- Choose a place on your computer to save it.
- Click Save.
- Type a descriptive name for the backup. By default, the environment name and current date is entered as the backup name.
- Choose whether to overwrite an existing environment backup file on Nucleus. Each backup name must be unique.
- Click Backup.
Importing an environment¶
Each environment has a YAML-formatted configuration file. If someone has given you an environment file that you want to use—for example my-environment-file.yml —and you have saved it to your computer, you can import it into Navigator. Furthermore, if you have backed up an environment either locally or to Nucleus, you can import it onto your local computer with Navigator.
At the bottom of the environments list, select Import.
In the Import Environment dialog, choose whether to import from your Local drive or from Anaconda Nucleus.
Select the corresponding folder icon to choose the environment you want to import.

Type a descriptive name for the new environment, or use the existing name. Each environment name must be unique.
Choose whether or not to overwrite an existing environment with your import.
Click Import.
Your newly imported environment will appear in the environments list.
Removing an environment¶
In Navigator
- In the environments list, select the environment you want to remove.
- At the bottom of the list, click Remove.
Removing an environment in Navigator only removes your local copy. It will not remove or delete environments you have backed up to Nucleus.

In Nucleus
- In a browser, open Anaconda Nucleus.
- Sign in using your email address and password.
- From your profile in the top-right corner, navigate to Subscriptions.
- Select the Environments page.
- Select Delete in the row associated with the environment you wish to remove.
Removing an environment in Nucleus only removes it from Nucleus. It does not affect any local copies.

Advanced environment management¶
Navigator provides a convenient graphical interface for managing conda environments, channels, and packages. If you’re comfortable working with Anaconda prompt (or terminal on Linux or macOS), you can access additional, advanced management features. To learn more, see Managing environments in the conda documentation.
8 ключевых команд для управления средами Conda
Виртуальные среды — не самая простая концепция для новичков в Python. Как правило, при установке ПО, например Microsoft Office и Evernote, большинство из нас придерживаются стандартной конфигурации, предполагающей применение ПО всеми пользователями ПК. Иначе говоря, на системном уровне устанавливается всего одна копия программы, доступ к которой получают все пользователи.
У многих из нас эта привычка формировалась годами с момента обучения программированию. Сначала мы учились устанавливать на ПК сам Python, а затем напрямую в систему — его пакеты. Чем больше мы с ним работали, тем большее число различных пакетов требовалось для решения широкого спектра задач, но по ходу стали возникать определенные сложности.
Пакет А зависит от пакета В с версией 2.0, поэтому вместе с первым из них на системном уровне устанавливается и второй. Однако другому проекту требуется пакет С, зависящий от пакета В с версией 2.5. При установке С в соответствии с его требованиями система обновит В до версии 2.5. Но вот обновление пакета А для взаимодействия с пакетом В 2.5 не произошло, что чревато проблемами на этапе работы с A.
С такого рода сложностями рано или поздно сталкиваются многие начинающие программисты Python. Помимо конфликтов зависимостей есть еще проекты, требующие разных его версий. Например, возможна ситуация, в которой ранее разработанные проекты продолжают использовать Python 2.x, а большинство других — 3.x. При этом некоторые из тех, что придерживаются версии 3.x., могут работать с Python 3.4, а другие требуют 3.5+. Следовательно, если для всех проектов на системном уровне установлен только Python, то конфликты его версий могут стать камнем преткновения.
В такой ситуации на помощь приходят среды Conda . Conda — это комплексный инструмент управления пакетами и средой, востребованный специалистами по данным. Кроме того, он оптимизирует библиотеки, связанные с наукой о данных, такие как NumPy, SciPy и TensorFlow, которые максимально увеличивают производительность имеющегося оборудования для обеспечения наилучшей вычислительной мощности (более подробная информация предоставлена на сайте Conda). Этот инструмент позволяет создавать изолированные среды для проектов, которые могут включать не только разные пакеты, но даже разные версии Python.
С подробной инструкций установки Conda на ПК можно ознакомиться на официальном сайте. Различают две версии данного инструмента: более компактный Miniconda, предоставляющий Conda и его зависимости, и Anaconda, включающий гораздо большее число пакетов, необходимых в научных исследованиях. После установки Conda вы можете выполнить следующую команду в терминале (или в другом инструменте командной строки на свое усмотрение):
В результате вы увидите версию Conda, установленную на вашем ПК. А это значит, что у нас все готово для работы. Далее мы рассмотрим важнейшие команды для управления средами в большинстве случаев.
1. Проверка доступных сред
Для начала выясним, какие среды находятся в нашем распоряжении. Выполняем следующую команду:
Предположим, вы только что установили Conda, тогда непременно увидите вот такой результат:
- base — среда по умолчанию, созданная Conda в процессе установки.
- Символ * указывает на то, что эта конкретная среда является активной.
- Путь показывает физическую директорию среды и связанные с ней пакеты.
Вышеуказанная команда проверки применяется для обзора сред Conda, доступных на ПК.
2. Создание новой среды
Для создания новой среды существует следующая команда:
- Флаг —name говорит о намерении указать имя новой среды. В данном случае она будет называться firstenv .
- Вместо —name возможен краткий вариант -n .
Эту команду можно расширить, чтобы установить дополнительные пакеты в процессе создания среды, к примеру NumPy и Requests :
Более того, у нас даже есть возможность указать конкретные версии этих пакетов, как показано ниже:
После установки можно удостовериться в успешном создании среды с помощью команды conda env list , отображающей firstenv в списке.
Если вы в курсе, какие пакеты необходимы для среды, то в процессе ее создания можно установить сразу их все. Это позволит избежать конфликтов зависимостей, к которым могут привести отдельные установки.
3. Активация среды
Как только вы создали среду, самое время в нее войти. На профессиональном языке этот процесс называется “активацией”. Выполняем код:
После выполнения вы заметите, что в начале строки появилось название среды (firstenv) или (your-own-env-name) в случае выбора другого имени, как показано ниже:
Поскольку среда firstenv уже активирована, попробуйте ради интереса снова выполнить conda env list . Вы увидите, что в строке firstenv появится символ * .
4. Установка, обновление и удаление пакетов
В уже существующей среде вы можете установить дополнительные пакеты, которые забыли указать при ее создании. Для этого существуют несколько способов в зависимости от доступности пакетов.
Сначала попробуем выполнить команду, устанавливающую пакет из предустановленного канала Anaconda. Отметим, что при желании вслед за именем пакета можно указать его версию.
Однако в канале Anaconda может не оказаться конкретного пакета. В таком случае есть вариант с применением стандартного канала conda-forge , как показано ниже. —channel или просто -c обозначает канал, из которого извлекается пакет.
Еще один важный канал — широко известный PyPI (каталог пакетов Python), доступный через инструмент управления пакетами pip , нативно поддерживаемый Conda. Рассмотрим простой пример:
Несмотря на то, что пакеты можно установить из множества каналов, желательно брать их из Anaconda, так как здесь их производительность была оптимизирована наилучшим образом. Дополнительная информация о каналах доступна на сайте.
В зависимости от установочного канала для обновления пакета достаточно лишь заменить install на команду update .
Для удаления пакета воспользуйтесь командой uninstall , как показано ниже. Отметим, что иначе она называется remove , например conda remove pandas .
5. Проверка установленных пакетов
По ходу работы в среде число пакетов возрастает, и в какой-то момент возникает необходимость проверить, какие из них уже установлены. Для этого выполняем следующую команду:
В результате вы увидите подобное:
Обратите внимание, что список указывает, из какого канала устанавливаются пакеты. В данном случае в нашем распоряжении пакеты из PyPI и conda-forge . Отсутствие информации о канале означает, что по умолчанию пакеты устанавливаются из Anaconda.
Если чрезмерная длина списка усложняет поиск конкретного пакета, можно проверить информацию только по одному, выполнив команду:
6. Деактивация среды
Закончив работу, вы покидаете текущую среду или, опираясь на терминологию, деактивируете ее. Для этой цели существует команда:
Вы заметите отсутствие префикса (firstenv) в сообщении командной строки. Ради интереса можете выполнить conda env list , чтобы убедиться, что среда firstenv больше не обозначена символом * , указывающим на ее активность.
7. Воссоздание сред
Воспроизводимость — вот главная цель, к достижению которой стремятся Conda и другие инструменты управления средой, чтобы обеспечить качественное выполнение кода не только на личном ПК, но и на машинах коллег по команде. Вот почему так важно иметь возможность воссоздавать ту же самую среду на другом компьютере. Рассмотрим несколько полезных команд, применяемых для этой цели.
Как только вы вошли в виртуальную среду, выполните:
Указанная команда создает в текущей директории файл требований, содержащий всю информацию по рабочей среде: имя, зависимости и установочные каналы. Вы можете открыть этот текстовой файл и поизучать его.
Этим файлом вы делитесь со всеми, кто хочет воссоздать такую же среду. Для его использования достаточно выполнить нижеследующую команду. При необходимости для обеспечения работоспособности данный файл можно подредактировать, например изменить имя среды.
Флаг -f говорит о намерении создать среду из конкретного файла. Перейдите в директорию, содержащую environment.yml , и выполните команду conda env create .
8. Удаление сред
Для удаления среды, в которой больше нет необходимости, выполняем команду:
- Флаг -n указывает на имя среды.
- Флаг -all означает, что будут удалены не только все пакеты, но и сама среда.
Ради интереса выполните conda env list , чтобы убедиться, что удаление среды прошло успешно.
Заключение
В статье были рассмотрены 8 основных команд Conda (но фактически их было больше). Надеюсь, они помогут вам начать работу с этим инструментом для управления средами в проектах науки о данных. Подведем краткие итоги:
Managing environments
With conda, you can create, export, list, remove, and update environments that have different versions of Python and/or packages installed in them. Switching or moving between environments is called activating the environment. You can also share an environment file.
There are many options available for the commands described on this page. For details, see Command reference .
conda activate and conda deactivate only work on conda 4.6 and later versions. For conda versions prior to 4.6, run:
-
Windows: activate or deactivate
-
Linux and macOS: source activate or source deactivate
Creating an environment with commands
By default, environments are installed into the envs directory in your conda directory. See Specifying a location for an environment or run conda create —help for information on specifying a different path.
Use the terminal or an Anaconda Prompt for the following steps:
To create an environment:
Replace myenv with the environment name.
When conda asks you to proceed, type y :
This creates the myenv environment in /envs/ . No packages will be installed in this environment.
To create an environment with a specific version of Python:
To create an environment with a specific package:
To create an environment with a specific version of a package:
To create an environment with a specific version of Python and multiple packages:
Tip
Install all the programs that you want in this environment at the same time. Installing 1 program at a time can lead to dependency conflicts.
To automatically install pip or another program every time a new environment is created, add the default programs to the create_default_packages section of your .condarc configuration file. The default packages are installed every time you create a new environment. If you do not want the default packages installed in a particular environment, use the —no-default-packages flag:
You can add much more to the conda create command. For details, run conda create —help .
Creating an environment from an environment.yml file
Use the terminal or an Anaconda Prompt for the following steps:
Create the environment from the environment.yml file:
The first line of the yml file sets the new environment’s name. For details see Creating an environment file manually .
Activate the new environment: conda activate myenv
Verify that the new environment was installed correctly:
You can also use conda info —envs .
Specifying a location for an environment
You can control where a conda environment lives by providing a path to a target directory when creating the environment. For example, the following command will create a new environment in a subdirectory of the current working directory called envs :
You then activate an environment created with a prefix using the same command used to activate environments created by name:
Specifying a path to a subdirectory of your project directory when creating an environment has the following benefits:
-
It makes it easy to tell if your project uses an isolated environment by including the environment as a subdirectory.
-
It makes your project more self-contained as everything, including the required software, is contained in a single project directory.
An additional benefit of creating your project’s environment inside a subdirectory is that you can then use the same name for all your environments. If you keep all of your environments in your envs folder, you’ll have to give each environment a different name.
There are a few things to be aware of when placing conda environments outside of the default envs folder.
Conda can no longer find your environment with the —name flag. You’ll generally need to pass the —prefix flag along with the environment’s full path to find the environment.
Specifying an install path when creating your conda environments makes it so that your command prompt is now prefixed with the active environment’s absolute path rather than the environment’s name.
After activating an environment using its prefix, your prompt will look similar to the following:
This can result in long prefixes:
To remove this long prefix in your shell prompt, modify the env_prompt setting in your .condarc file:
This will edit your .condarc file if you already have one or create a .condarc file if you do not.
Now your command prompt will display the active environment’s generic name, which is the name of the environment’s root folder:
Updating an environment
You may need to update your environment for a variety of reasons. For example, it may be the case that:
one of your core dependencies just released a new version (dependency version number update).
you need an additional package for data analysis (add a new dependency).
you have found a better package and no longer need the older package (add new dependency and remove old dependency).
If any of these occur, all you need to do is update the contents of your environment.yml file accordingly and then run the following command:
The —prune option causes conda to remove any dependencies that are no longer required from the environment.
Cloning an environment
Use the terminal or an Anaconda Prompt for the following steps:
You can make an exact copy of an environment by creating a clone of it:
Replace myclone with the name of the new environment. Replace myenv with the name of the existing environment that you want to copy.
To verify that the copy was made:
In the environments list that displays, you should see both the source environment and the new copy.
Building identical conda environments
You can use explicit specification files to build an identical conda environment on the same operating system platform, either on the same machine or on a different machine.
Use the terminal or an Anaconda Prompt for the following steps:
Run conda list —explicit to produce a spec list such as:
To create this spec list as a file in the current working directory, run:
You can use spec-file.txt as the filename or replace it with a filename of your choice.
An explicit spec file is not usually cross platform, and therefore has a comment at the top such as # platform: osx-64 showing the platform where it was created. This platform is the one where this spec file is known to work. On other platforms, the packages specified might not be available or dependencies might be missing for some of the key packages already in the spec.
To use the spec file to create an identical environment on the same machine or another machine:
To use the spec file to install its listed packages into an existing environment:
Conda does not check architecture or dependencies when installing from a spec file. To ensure that the packages work correctly, make sure that the file was created from a working environment, and use it on the same architecture, operating system, and platform, such as linux-64 or osx-64.
Activating an environment
Activating environments is essential to making the software in the environments work well. Activation entails two primary functions: adding entries to PATH for the environment and running any activation scripts that the environment may contain. These activation scripts are how packages can set arbitrary environment variables that may be necessary for their operation. You can also use the config API to set environment variables .
When installing Anaconda, you have the option to “Add Anaconda to my PATH environment variable.” This is not recommended because the add to PATH option appends Anaconda to PATH. When the installer appends to PATH, it does not call the activation scripts.
On Windows, PATH is composed of two parts, the system PATH and the user PATH. The system PATH always comes first. When you install Anaconda for Just Me, we add it to the user PATH. When you install for All Users, we add it to the system PATH. In the former case, you can end up with system PATH values taking precedence over our entries. In the latter case, you do not. We do not recommend multi-user installs.
Activation prepends to PATH. This only takes effect when you have the environment active so it is local to a terminal session, not global.
To activate an environment: conda activate myenv
Replace myenv with the environment name or directory path.
Conda prepends the path name myenv onto your system command.
You may receive a warning message if you have not activated your environment:
If you receive this warning, you need to activate your environment. To do so on Windows, run: c:\Anaconda3\Scripts\activate base in Anaconda Prompt.
Windows is extremely sensitive to proper activation. This is because the Windows library loader does not support the concept of libraries and executables that know where to search for their dependencies (RPATH). Instead, Windows relies on a dynamic-link library search order.
If environments are not active, libraries won’t be found and there will be lots of errors. HTTP or SSL errors are common errors when the Python in a child environment can’t find the necessary OpenSSL library.
Conda itself includes some special workarounds to add its necessary PATH entries. This makes it so that it can be called without activation or with any child environment active. In general, calling any executable in an environment without first activating that environment will likely not work. For the ability to run executables in activated environments, you may be interested in the conda run command.
If you experience errors with PATH, review our troubleshooting .
Conda init
Earlier versions of conda introduced scripts to make activation behavior uniform across operating systems. Conda 4.4 allowed conda activate myenv . Conda 4.6 added extensive initialization support so that conda works faster and less disruptively on a wide variety of shells (bash, zsh, csh, fish, xonsh, and more). Now these shells can use the conda activate command. Removing the need to modify PATH makes conda less disruptive to other software on your system. For more information, read the output from conda init —help .
One setting may be useful to you when using conda init is:
This setting controls whether or not conda activates your base environment when it first starts up. You’ll have the conda command available either way, but without activating the environment, none of the other programs in the environment will be available until the environment is activated with conda activate base . People sometimes choose this setting to speed up the time their shell takes to start up or to keep conda-installed software from automatically hiding their other software.
Nested activation
By default, conda activate will deactivate the current environment before activating the new environment and reactivate it when deactivating the new environment. Sometimes you may want to leave the current environment PATH entries in place so that you can continue to easily access command-line programs from the first environment. This is most commonly encountered when common command-line utilities are installed in the base environment. To retain the current environment in the PATH, you can activate the new environment using:
If you wish to always stack when going from the outermost environment, which is typically the base environment, you can set the auto_stack configuration option:
You may specify a larger number for a deeper level of automatic stacking, but this is not recommended since deeper levels of stacking are more likely to lead to confusion.
Environment variable for DLL loading verification
If you don’t want to activate your environment and you want Python to work for DLL loading verification, then follow the troubleshooting directions .
If you choose not to activate your environment, then loading and setting environment variables to activate scripts will not happen. We only support activation.
Deactivating an environment
To deactivate an environment, type: conda deactivate
Conda removes the path name for the currently active environment from your system command.
To simply return to the base environment, it’s better to call conda activate with no environment specified, rather than to try to deactivate. If you run conda deactivate from your base environment, you may lose the ability to run conda at all. Don’t worry, that’s local to this shell — you can start a new one. However, if the environment was activated using —stack (or was automatically stacked) then it is better to use conda deactivate .
Determining your current environment
Use the terminal or an Anaconda Prompt for the following steps.
By default, the active environment—the one you are currently using—is shown in parentheses () or brackets [] at the beginning of your command prompt:
If you do not see this, run:
In the environments list that displays, your current environment is highlighted with an asterisk (*).
By default, the command prompt is set to show the name of the active environment. To disable this option:
To re-enable this option:
Viewing a list of your environments
To see a list of all of your environments, in your terminal window or an Anaconda Prompt, run:
A list similar to the following is displayed:
If this command is run by an administrator, a list of all environments belonging to all users will be displayed.
Viewing a list of the packages in an environment
To see a list of all packages installed in a specific environment:
If the environment is not activated, in your terminal window or an Anaconda Prompt, run:
If the environment is activated, in your terminal window or an Anaconda Prompt, run:
To see if a specific package is installed in an environment, in your terminal window or an Anaconda Prompt, run:
Using pip in an environment
To use pip in your environment, in your terminal window or an Anaconda Prompt, run:
Issues may arise when using pip and conda together. When combining conda and pip, it is best to use an isolated conda environment. Only after conda has been used to install as many packages as possible should pip be used to install any remaining software. If modifications are needed to the environment, it is best to create a new environment rather than running conda after pip. When appropriate, conda and pip requirements should be stored in text files.
We recommend that you:
Install as many requirements as possible with conda then use pip.
Pip should be run with —upgrade-strategy only-if-needed (the default).
Do not use pip with the —user argument, avoid all users installs.
Create a conda environment to isolate any changes pip makes.
Environments take up little space thanks to hard links.
Care should be taken to avoid running pip in the root environment.
Once pip has been used, conda will be unaware of the changes.
To install additional conda packages, it is best to recreate the environment.
Package requirements can be passed to conda via the —file argument.
Pip accepts a list of Python packages with -r or —requirements .
Conda env will export or create environments based on a file with conda and pip requirements.
Setting environment variables
If you want to associate environment variables with an environment, you can use the config API. This is recommended as an alternative to using activate and deactivate scripts since those are an execution of arbitrary code that may not be safe.
First, create your environment and activate it:
To list any variables you may have, run conda env config vars list .
To set environment variables, run conda env config vars set my_var=value .
Once you have set an environment variable, you have to reactivate your environment: conda activate test-env .
To check if the environment variable has been set, run echo $my_var ( echo %my_var% on Windows) or conda env config vars list .
When you deactivate your environment, you can use those same commands to see that the environment variable goes away.
You can specify the environment you want to affect using the -n and -p flags. The -n flag allows you to name the environment and -p allows you to specify the path to the environment.
To unset the environment variable, run conda env config vars unset my_var -n test-env .
When you deactivate your environment, you can see that environment variable goes away by rerunning echo my_var or conda env config vars list to show that the variable name is no longer present.
Environment variables set using conda env config vars will be retained in the output of conda env export . Further, you can declare environment variables in the environment.yml file as shown here:
Saving environment variables
Conda environments can include saved environment variables.
Suppose you want an environment "analytics" to store both a secret key needed to log in to a server and a path to a configuration file. The sections below explain how to write a script named env_vars to do this on Windows and macOS or Linux .
This type of script file can be part of a conda package, in which case these environment variables become active when an environment containing that package is activated.
You can name these scripts anything you like. However, multiple packages may create script files, so be sure to use descriptive names that are not used by other packages. One popular option is to give the script a name in the form packagename-scriptname.sh , or on Windows, packagename-scriptname.bat .
Windows
Locate the directory for the conda environment in your Anaconda Prompt by running in the command shell %CONDA_PREFIX% .
Enter that directory and create these subdirectories and files:
Edit .\etc\conda\activate.d\env_vars.bat as follows:
Edit .\etc\conda\deactivate.d\env_vars.bat as follows:
When you run conda activate analytics , the environment variables MY_KEY and MY_FILE are set to the values you wrote into the file. When you run conda deactivate , those variables are erased.
macOS and Linux
Locate the directory for the conda environment in your terminal window by running in the terminal echo $CONDA_PREFIX .
Enter that directory and create these subdirectories and files:
Edit ./etc/conda/activate.d/env_vars.sh as follows:
Edit ./etc/conda/deactivate.d/env_vars.sh as follows:
When you run conda activate analytics , the environment variables MY_KEY and MY_FILE are set to the values you wrote into the file. When you run conda deactivate , those variables are erased.
Sharing an environment
You may want to share your environment with someone else—for example, so they can re-create a test that you have done. To allow them to quickly reproduce your environment, with all of its packages and versions, give them a copy of your environment.yml file.
Exporting the environment.yml file
If you already have an environment.yml file in your current directory, it will be overwritten during this task.
Activate the environment to export: conda activate myenv
Replace myenv with the name of the environment.
Export your active environment to a new file:
This file handles both the environment’s pip packages and conda packages.
Email or copy the exported environment.yml file to the other person.
Exporting an environment file across platforms
If you want to make your environment file work across platforms, you can use the conda env export —from-history flag. This will only include packages that you’ve explicitly asked for, as opposed to including every package in your environment.
For example, if you create an environment and install Python and a package:
This will download and install numerous additional packages to solve for dependencies. This will introduce packages that may not be compatible across platforms.
If you use conda env export , it will export all of those packages. However, if you use conda env export —from-history , it will only export those you specifically chose:
If you installed Anaconda 2019.10 on macOS, your prefix may be /Users/username/opt/envs/env-name .
Creating an environment file manually
You can create an environment file ( environment.yml ) manually to share with others.
EXAMPLE: A simple environment file:
EXAMPLE: A more complex environment file:
Using wildcards
Note the use of the wildcard * when defining a few of the versions in the complex environment file. Keeping the major and minor versions fixed while allowing the patch to be any number allows you to use your environment file to get any bug fixes while still maintaining consistency in your environment. For more information on package installation values, see Package search and install specifications .
Specifying channels outside of "channels"
You may occasionally want to specify which channel conda will use to install a specific package. To accomplish this, use the channel::package syntax in dependencies: , as demonstrated above with conda-forge::numpy (version numbers optional). The specified channel does not need to be present in the channels: list, which is useful if you want some—but not all—packages installed from a community channel such as conda-forge .
You can exclude the default channels by adding nodefaults to the channels list.
This is equivalent to passing the —override-channels option to most conda commands.
Adding nodefaults to the channels list in environment.yml is similar to removing defaults from the channels list in the .condarc file. However, changing environment.yml affects only one of your conda environments while changing .condarc affects them all.
For details on creating an environment from this environment.yml file, see Creating an environment from an environment.yml file .
Restoring an environment
Conda keeps a history of all the changes made to your environment, so you can easily "roll back" to a previous version. To list the history of each change to the current environment: conda list —revisions
To restore environment to a previous revision: conda install —revision=REVNUM or conda install —rev REVNUM .
Replace REVNUM with the revision number.
Example: If you want to restore your environment to revision 8, run conda install —rev 8 .
Removing an environment
To remove an environment, in your terminal window or an Anaconda Prompt, run:
You may instead use conda env remove —name myenv .
To verify that the environment was removed, in your terminal window or an Anaconda Prompt, run:
The environments list that displays should not show the removed environment.