How to activate conda environment
How to activate conda environment
How to activate conda environment in VS code
Before we begin: I am using windows 10, and this worked for me. I believe mac/linux users can benefit from this article as well.
You need to have the Python extension installed in VS code.
When you want your python to run in VS code you need to configure a python interpreter for it. You may have virtual environments with different versions of python or different packages installed, each environment has its own interpreter. Now, in the case you run your virtual environments through conda — configuring this setting is not straight forward.
You need to 1) set your interpreter and 2) MAKE SURE YOUR CONDA ENVIRONMENT IS ACTIVATED.
1. Setting your python interpreter
Setting your interpreter is pretty easy, you got a few ways to do it (taken from VS code documentation):
a) Open the Command Pallete (Ctrl/Cmd + Shift + P) and type “Python: Select Interpreter”, select the command and it should present you a list of available interpreters (the ones Python extension has detected)
b) On the status bar, in the bottom left corner of the screen, use the Select Python Interpreter option, if available (it may already show a selected interpreter). Then select from the list presented to you.
c) Change your `python.pythonpath` manually in the settings —to get to settings hit Ctrl/Cmd +, (i.e. Ctrl/Cmd + comma) then select w orkspace settings tab and set:
Note: If you select an interpreter without a workspace folder open, VS Code sets python.pythonPath in your user settings instead, which sets the default interpreter for VS Code in general. The user setting makes sure you always have a default interpreter for Python projects. The workspace settings lets you override the user setting.
2. Make sure your conda environment is activated
Making sure your conda environment is activated can be done using shell arguments. There should be an activate.bat script that’s starting the anaconda prompt in your Anaconda/Miniconda installation, in the Scripts folder. This activate.bat script location looks something like this:
The command to start the anaconda prompt in terminal should look something like this:
This activates conda default environment, once you are in there you can change environment with the activate command:
Now you need to change the workspace settings in VS code so it will run these commands for your every time you start a terminal.
Notice that “/K” argument works for windows command line, for mac/linux terminal it should be a bit different.
If you need to activate a specific environment add “& conda activate ”:
On windows I recommend setting your VS code integrated terminal to your default cmd.exe, other terminal might not work as expected. To do that, go to user settings in VS code and set:
Now every time you open your integrated terminal in your workspace it will have your conda environment activated. To run a python file you can right click in the editor and select Run Python File in Terminal.
Bonus: If you want to run your python code with the code runner extension, in your workspace settings insert:
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 на ПК можно ознакомиться на официальном сайте. Различают две версии данного инструмента: более компактный Miniconda, предоставляющий Conda и его зависимости, и Anaconda, включающий гораздо большее число пакетов, необходимых в научных исследованиях. После установки Conda вы можете выполнить следующую команду в терминале (или в другом инструменте командной строки на свое усмотрение):
В результате вы увидите версию Conda, установленную на вашем ПК. А это значит, что у нас все готово для работы. Далее мы рассмотрим важнейшие команды для управления средами в большинстве случаев.
1. Проверка доступных сред
Для начала выясним, какие среды находятся в нашем распоряжении. Выполняем следующую команду:
Предположим, вы только что установили Conda, тогда непременно увидите вот такой результат:
Вышеуказанная команда проверки применяется для обзора сред Conda, доступных на ПК.
2. Создание новой среды
Для создания новой среды существует следующая команда:
Эту команду можно расширить, чтобы установить дополнительные пакеты в процессе создания среды, к примеру NumPy и Requests :
Более того, у нас даже есть возможность указать конкретные версии этих пакетов, как показано ниже:
Если вы в курсе, какие пакеты необходимы для среды, то в процессе ее создания можно установить сразу их все. Это позволит избежать конфликтов зависимостей, к которым могут привести отдельные установки.
3. Активация среды
Как только вы создали среду, самое время в нее войти. На профессиональном языке этот процесс называется “активацией”. Выполняем код:
После выполнения вы заметите, что в начале строки появилось название среды (firstenv) или (your-own-env-name) в случае выбора другого имени, как показано ниже:
4. Установка, обновление и удаление пакетов
В уже существующей среде вы можете установить дополнительные пакеты, которые забыли указать при ее создании. Для этого существуют несколько способов в зависимости от доступности пакетов.
Сначала попробуем выполнить команду, устанавливающую пакет из предустановленного канала Anaconda. Отметим, что при желании вслед за именем пакета можно указать его версию.
Несмотря на то, что пакеты можно установить из множества каналов, желательно брать их из Anaconda, так как здесь их производительность была оптимизирована наилучшим образом. Дополнительная информация о каналах доступна на сайте.
5. Проверка установленных пакетов
По ходу работы в среде число пакетов возрастает, и в какой-то момент возникает необходимость проверить, какие из них уже установлены. Для этого выполняем следующую команду:
В результате вы увидите подобное:
Если чрезмерная длина списка усложняет поиск конкретного пакета, можно проверить информацию только по одному, выполнив команду:
6. Деактивация среды
Закончив работу, вы покидаете текущую среду или, опираясь на терминологию, деактивируете ее. Для этой цели существует команда:
7. Воссоздание сред
Воспроизводимость — вот главная цель, к достижению которой стремятся Conda и другие инструменты управления средой, чтобы обеспечить качественное выполнение кода не только на личном ПК, но и на машинах коллег по команде. Вот почему так важно иметь возможность воссоздавать ту же самую среду на другом компьютере. Рассмотрим несколько полезных команд, применяемых для этой цели.
Как только вы вошли в виртуальную среду, выполните:
Указанная команда создает в текущей директории файл требований, содержащий всю информацию по рабочей среде: имя, зависимости и установочные каналы. Вы можете открыть этот текстовой файл и поизучать его.
Этим файлом вы делитесь со всеми, кто хочет воссоздать такую же среду. Для его использования достаточно выполнить нижеследующую команду. При необходимости для обеспечения работоспособности данный файл можно подредактировать, например изменить имя среды.
8. Удаление сред
Для удаления среды, в которой больше нет необходимости, выполняем команду:
Заключение
В статье были рассмотрены 8 основных команд Conda (но фактически их было больше). Надеюсь, они помогут вам начать работу с этим инструментом для управления средами в проектах науки о данных. Подведем краткие итоги:
How to activate an Anaconda environment
I’m on Windows 8, using Anaconda 1.7.5 64bit.
I created a new Anaconda environment with
This worked well (there is a folder with a new python distribution). conda tells me to type
to activate the environment, however this returns:
No environment named «C:\PR\temp\venv\test» exists in C:\PR\Anaconda\envs
How can I activate the environment? What am I doing wrong?
12 Answers 12
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If this happens you would need to set the PATH for your environment (so that it gets the right Python from the environment and Scripts\ on Windows).
Imagine you have created an environment called py33 by using:
Here the folders are created by default in Anaconda\envs, so you need to set the PATH as:
Now it should work in the command window:
The line above is the Windows equivalent to the code that normally appears in the tutorials for Mac and Linux:
Use cmd instead of Powershell! I spent 2 hours before I switched to cmd and then it worked!
create Environment:
see list of conda environments:
activate your environment:
That’s all folks
Should be changed to
This only adds the conda command to the path, but does not yet activate the base environment (which was previously called root ). To do also that, add another line
(This answer is valid for Linux, but it might be relevant for Windows and Mac as well)
All the former answers seem to be outdated.
conda activate was introduced in conda 4.4 and 4.6.
conda activate : The logic and mechanisms underlying environment activation have been reworked. With conda 4.4, conda activate and conda deactivate are now the preferred commands for activating and deactivating environments. You’ll find they are much more snappy than the source activate and source deactivate commands from previous conda versions. The conda activate command also has advantages of (1) being universal across all OSes, shells, and platforms, and (2) not having path collisions with scripts from other packages like python virtualenv’s activate script.
Getting started with condaпѓЃ
Conda is a powerful package manager and environment manager that you use with command line commands at the Anaconda Prompt for Windows, or in a terminal window for macOS or Linux.
This 20-minute guide to getting started with conda lets you try out the major features of conda. You should understand how conda works when you finish this guide.
SEE ALSO: Getting started with Anaconda Navigator, a graphical user interface that lets you use conda in a web-like interface without having to enter manual commands. Compare the Getting started guides for each to see which program you prefer.
Before you startпѓЃ
You should have already installed Anaconda.
ContentsпѓЃ
Starting conda on Windows, macOS, or Linux. 2 MINUTES
TOTAL TIME: 20 MINUTES
Starting condaпѓЃ
Windows
From the Start menu, search for and open «Anaconda Prompt.»
On Windows, all commands below are typed into the Anaconda Prompt window.
MacOS
Open Launchpad, then click the terminal icon.
On macOS, all commands below are typed into the terminal window.
Linux
Open a terminal window.
On Linux, all commands below are typed into the terminal window.
Managing condaпѓЃ
Verify that conda is installed and running on your system by typing:
Conda displays the number of the version that you have installed. You do not need to navigate to the Anaconda directory.
EXAMPLE: conda 4.7.12
If you get an error message, make sure you closed and re-opened the terminal window after installing, or do it now. Then verify that you are logged into the same user account that you used to install Anaconda or Miniconda.
Update conda to the current version. Type the following:
Conda compares versions and then displays what is available to install.
If a newer version of conda is available, type y to update:
We recommend that you always keep conda updated to the latest version.
Managing environmentsпѓЃ
Conda allows you to create separate environments containing files, packages, and their dependencies that will not interact with other environments.
Create a new environment and install a package in it.
We will name the environment snowflakes and install the package BioPython. At the Anaconda Prompt or in your terminal window, type the following:
Conda checks to see what additional packages («dependencies») BioPython will need, and asks if you want to proceed:
Type «y» and press Enter to proceed.
To use, or «activate» the new environment, type the following:
Windows: conda activate snowflakes
macOS and Linux: conda activate snowflakes
conda activate only works on conda 4.6 and later versions.
For conda versions prior to 4.6, type:
Windows: activate snowflakes
macOS and Linux: source activate snowflakes
Now that you are in your snowflakes environment, any conda commands you type will go to that environment until you deactivate it.
To see a list of all your environments, type:
A list of environments appears, similar to the following:
The active environment is the one with an asterisk (*).
Change your current environment back to the default (base): conda activate
For versions prior to conda 4.6, use:
macOS, Linux: source activate
Managing PythonпѓЃ
When you create a new environment, conda installs the same Python version you used when you downloaded and installed Anaconda. If you want to use a different version of Python, for example Python 3.5, simply create a new environment and specify the version of Python that you want.
Create a new environment named «snakes» that contains Python 3.9:
When conda asks if you want to proceed, type «y» and press Enter.
Activate the new environment:
Windows: conda activate snakes
macOS and Linux: conda activate snakes
conda activate only works on conda 4.6 and later versions.
For conda versions prior to 4.6, type:
Windows: activate snakes
macOS and Linux: source activate snakes
Verify that the snakes environment has been added and is active:
Conda displays the list of all environments with an asterisk (*) after the name of the active environment:
The active environment is also displayed in front of your prompt in (parentheses) or [brackets] like this:
Verify which version of Python is in your current environment:
Deactivate the snakes environment and return to base environment: conda activate
For versions prior to conda 4.6, use:
macOS, Linux: source activate
Managing packagesпѓЃ
In this section, you check which packages you have installed, check which are available and look for a specific package and install it.
Check to see if a package you have not installed named «beautifulsoup4» is available from the Anaconda repository (must be connected to the Internet):
Conda displays a list of all packages with that name on the Anaconda repository, so we know it is available.
Install this package into the current environment:
Check to see if the newly installed program is in this environment:
9 Answers 9
It looks like the accepted answers might be out of date. From the docs:
If your shell is Bash or a Bourne variant, enable conda for the current user with
or, for all users, enable conda with
The options above will permanently enable the ‘conda’ command, but they do NOT put conda’s base (root) environment on PATH. To do so, run
in your terminal, or to put the base environment on PATH permanently, run
Previous to conda 4.4, the recommended way to activate conda was to modify PATH in your
/.bashrc file. You should manually remove the line that looks like
^^^ The above line should NO LONGER be in your
For bash use:
Reload:
Test (install Spyder):
Run Spyder
This points to the ‘conda’ executable, and sets up the path to handle conda activate.
Add this line after the export command:
from there you can source
/.bashrc to load the environment to the current shell.
Correct Fix
(works for versions >= 4.6)
To deactivate just do the same but with false. Obviously:
Quick & Dirty Fix #1
Quick & Dirty Fix #2
/miniconda3 ), run the install script again and pay attention to the prompt as it will aks you if you want to autostart it.
Источники информации:
- http://medium.com/nuances-of-programming/8-%D0%BA%D0%BB%D1%8E%D1%87%D0%B5%D0%B2%D1%8B%D1%85-%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4-%D0%B4%D0%BB%D1%8F-%D1%83%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F-%D1%81%D1%80%D0%B5%D0%B4%D0%B0%D0%BC%D0%B8-conda-a916bf1f3d05
- http://stackoverflow.com/questions/20081338/how-to-activate-an-anaconda-environment
- http://docs.conda.io/projects/conda/en/latest/user-guide/getting-started.html
- http://askubuntu.com/questions/849470/how-do-i-activate-a-conda-environment-in-my-bashrc