Visual Code how can I activate the virtual environment automatically? - python

Maybe a simple question, but I cannot figure it out. I work within Visual Studio Code on a MacBook. Within a directory I create a virtual environment and have activated that with source .venv/bin/activate scripts and everything works fine.
In the terminal I see (.venv) (base) gaston#MacBook-Pro WebScraping %
When I start visual code another time and open this same directory I do not see the (.venv) so I again give manually the command to activate.
My question is there a way to activate the virtual environment automatically when opening the directory?

VS Code Default Python Interpreter Path
You can do this in a number of ways. If your goal is to have the virtual environment selected immediately at the launch of VS Code, you will have to target that virtual environment as the Python Interpreter in VSC.
https://code.visualstudio.com/docs/python/environments
System Preferences->Settings->Python: Default Interpreter Path
You'll want to point it to your virtualenv Python installation, likely something like:
envFolder/bin/python3
VS Code Launch Configuration Python Interpreter
You can also set a specific launch configuration so that VSCode will still use your system Python instance by default; however, specific launch configurations will have the virtual environment specified.
https://code.visualstudio.com/docs/python/debugging

I did something within settings and now it works.
When I open VSC now it opens the directory and the right environment, just the way I wanted it.
Took me some while to figure what finally did the trick:
I opened settings Command + , typed env in the search box. Scrolled through the results until I saw:
Python > Terminal: Activate Env In Current Terminal
and checked the checkbox. That solved my problem.

Related

Use Visual Studio Code with Miniconda on macOS

On my Mac, I installed Python using Miniconda and I have also installed various Python packages using conda. In the Mac Terminal app, my base conda environment is active and when I run Python it correctly uses the Miniconda version of Python as shown below:
In Visual Studio Code (VSCode), I have selected the Miniconda version of Python using the Python Interpreter setting. The correct version of Python and conda environment is shown at the bottom of the window:
However, when I use the built-in terminal in VSCode it still uses the macOS Python even though it shows the base conda environment is active:
I'm using the Python, One Dark Pro, and Jupyter extensions in VSCode. Also, the $PATH in the VSCode terminal and in the Mac terminal app returns the following:
# VSCode terminal
base ❯ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/Library/Apple/usr/bin:/Users/gavinw/miniconda3/bin:/Users/gavinw/miniconda3/condabin
# Mac terminal app
base ❯ echo $PATH
/Users/gavinw/miniconda3/bin:/Users/gavinw/miniconda3/condabin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/Library/Apple/usr/bin
How can I configure the Visual Studio Code terminal to use the Miniconda version of Python?
After selecting the Python that comes with conda, the Python interpreter will be displayed in the lower left corner of VSCode, and then use the shortcut key Ctrl+Shift+` to open a new VSCode terminal, (or click "Terminal", "New terminal") it will automatically enter the selected environment and activate it automatically.
The terminal uses whatever python environment your configured shell command is set to. It is in no way linked to the environment of VS Code
However, If you attempt to run a Python file, it will open up the terminal with the full path to the specified interpreter
These details are laid out in the docs
The Python extension uses the selected environment for running Python code (using the Python: Run Python File in Terminal command), providing language services (auto-complete, syntax checking, linting, formatting, etc.) when you have a .py file open in the editor, and opening a terminal with the Terminal: Create New Integrated Terminal command. In the latter case, VS Code automatically activated the selected environment.
Also, if using code command from an activated session...
launching VS Code from a shell in which a certain Python environment is activated does not automatically activate that environment in the default Integrated Terminal.
Otherwise, launching the desktop app directly would also not be done from an activated conda environment
You may want to check the value in your settings for "python.terminal.activateEnvironment", but I believe this only applies when you actually run a .py file

Visual Studio Code Python Interactive Window env different from selected?

I am using visual studio code to try and replace the Spyder IDE. To replicate Spyder's variable explorer, I am trying to leverage VS code's Python Interactive Window.
Upon launching Vs Code, I select my environment using "Select Interpreter" and then picking the env. This then changes at the bottom of the application as expected.
However, when I then try and run my code in the interactive window it appears to reference a different environment? It also keeps telling me to install ipykernel.
Is this functioning correctly? I do see an option to change the env in the interactive window but that doesn't do anything.enter image description here
I found a similar question here But I have ipykernel installed in my environment so I'm not sure why it wouldn't notice that? Is there another dependency?
Maybe we can simplify the problem.
Click top-right environment and changes it to which you want.
Start off by opening your Anaconda prompt and from there activate your virtual environment (type: conda activate my_env, replacing my_env with your environment name, and hit enter.)
Then type the command: 'code', which will open up VS Code from within your active virtual environment. Before this approach, also check that your VS Code settings.json file has the python path set correctly to your environment installation. Now it should work.
To see your install path: Anaconda is installed in your user home directory: Windows 10: C:\Users\\Anaconda3\

PyCharm not able to create conda environment

I'm pretty new to programming, so maybe there's something painfully obvious that I've missed, but I've searched a lot around for solutions to this issue without finding any.
I just got a new computer and installed Anaconda and PyCharm for Anaconda. I got it to work fine on my old computer, but when I try to open PyCharm now and create a project, it gets stuck on the creation of the conda environment. Apparently there's a new conda update, so I tried to update to this one in Spyder, which seemed to work fine, but when PyCharm tries creating a new environment, it gets stuck and only displays
"Creating Conda environment"
"$ conda update -n base -c defaults conda"
Does anybody know what's happening? I've tried just waiting it out, but it doesn't seem to be moving forward at all from that point. I've also uninstalled both Anaconda and PyCharm with all their plugins and reinstalling them, but to no avail.
Thanks for any help or input!
Sincerely, confused first year student
It appears that Sophie was able to get the conda environment up and running.
However, other newcomers might come across a similar problem with regards to setting up Anaconda for use within PyCharm. Therefore, I provide a guide below that I recently (today) used in order to accomplish this on a fresh install on a new computer. For this I decided to use PyCharm Community Edition 2018.3 and Anaconda3 version 2019.07. I performed this on Windows 10 Enterprise version 1903. I have also performed this procedure on Windows 7 Home Premium edition (some time ago).
This will enable you to use PyCharm and Anaconda together, so that you can:
Know the prerequisite steps leading up to creating a conda environment, and become familiar with the steps following this action with using Anaconda with PyCharm.
Use the Terminal window in PyCharm with packages that are installed with Anaconda's version of Python. You can then use both regular python and conda commands to view, update or install packages. For instance, depending on your preference, you could use 'pip list' (python command) or 'conda list' to list installed packages.
Use the Anaconda python interpreter as the default Python Console in PyCharm
To accomplish this, please follow these steps:
Install PyCharm, and import any settings file you may have from previous PyCharm installation on other computer (optional). Assuming you are starting fresh, create a new project and set the (default) project folder location.
Install Anaconda. My install location was set to C:\ProgramData\Anaconda3. Note that 'ProgramData' folder is hidden by default. You should enable viewing of hidden folders in windows explorer, if you need to manually browse for it. Upon installation, I decided to have the options Add Anaconda to my PATH environment variable and Register Anaconda as my default Python 3.7 set as deselected.
Open Windows Explorer and paste in C:\ProgramData\Anaconda3 (or your install directory) in the address bar. This should take you to that directory. Navigate to the environments folder named envs. Select the address bar and copy that address. I got C:\ProgramData\Anaconda3\envs. You will need this later.
Open program named Anaconda Navigator (Anaconda3). You should see this from the list of newly installed programs. Alternatively, search for it and open it. This will initialize some stuff (unknown to me) that I have found necessary to be able to complete this guide. For the next steps we dont need this program running. You could close it if you want.
Decide on a name for the (ana)conda environment that we will create. I used py37 for simplicity. You only need to do this once for the python projects you will make. It is possible to make more environments if you should need that for some python projects in the future.
Open program named Anaconda Prompt (Anaconda3), preferentially as administrator. Opening as administrator may prevent complications that could occur on some systems. To do so, search for the program and then right-click it, and choose Run as administrator.
Enter this command: conda create -n py37 python=3.7 anaconda. It should prompt you to install some packages. Enter y to accept and proceed with the setup. This step may take some time to finish. Once finished, it may show you the needed command to activate the environment. Don't activate it just yet, ie. ignore that message for now.
Assuming environment path C:\ProgramData\Anaconda3\envs and environment name py37, run the following command (alter as needed to match your environment path and name): set PATH=C:\ProgramData\Anaconda\envs\py37\Scripts;C:\ProgramData\Anaconda\envs\py37;%PATH%
Run this command: conda activate py37. This will activate your environment.
Navigate to a folder you can easily access, such as the Documents folder on your machine. To do so, execute this command: cd "C:\Users\YourUsername\Documents".
Execute the following command: echo %PATH% > path_value.txt. This will export "PATH" values to a text file that can be found in the Documents folder as path_value.txt. Open this file and copy the content within. This will be needed in the following steps with setting up PyCharm for use with the Anaconda environment.
In PyCharm, navigate to Settings - Tools - Terminal. Check that Start directory field contains the path of your project folder, ie. such as C:/Users/YourUsername/Documents/YourProjectFolderName. Then, select the folder icon for the Environment variables field. Click the plus symbol, and add a new entry with PATH and your path value (as found from the path_value.txt file) in the Name and Value fields, respectively.
In PyCharm, navigate to Settings - Project Interpreter - Add Python Interpreter - Conda Environment - Existing environment. Browse for C:\ProgramData\Anaconda3 (or your install directory). Select the file named python.exe. I chose to edit the Name field of this Anaconda python interpreter as Python 3.7 Anaconda.
In PyCharm, navigate to Settings - Build, Execution, Deployment - Console - Python Console. Check that the Python interpreter field contains Project Default (Python 3.7 Anaconda) or similar entry. The Environment variables input may be empty. Select the folder button next to it and add a new entry with PATH and your path value (as found from the path_value.txt file) in the Name and Value fields, respectively. Exactly the same entries as was inputted in step 12.
[Optional] In PyCharm, navigate to Settings and search for the Run context configuration option. Right click it and select a desired shortcut method. Personally I use a keyboard shortcut which is set to Ctrl+Shift+Less. Once the rest of these steps are followed, this will allow you to run the current python .py file you have open, without having to manually set up configuration options for it (through Add Configuration option, next to green play button, as seen if you have no configurations set up from before). It will force PyCharm to use the default project interpreter (which now is the desired Anaconda-delivered Python 3.7 installation) for whatever project you have open. To use it, just open a .py python file with some code inside, click anywhere inside of it, and then use your shortcut option.
[Note: If you skipped step 15, go to step 17] Run your python file with the method from step 15. This should automatically set up a run configuration option for that file. You may get an error of missing packages. Ignore that for now.
Select Edit Configuration or Add Configuration in the dropdown box next to the green play / run button. Open the Templates tree, then select Python. Check that the Python interpreter option contains Python 3.7 Anaconda or similar. The Environment variables field may contain PYTHONUNBUFFERED=1. Regardless, select the related folder button and add a new entry with PATH and your path value (as found from the path_value.txt file) in the Name and Value fields, respectively. Exactly the same as we did in steps 12 and 14.
Restart PyCharm to re-initialize the Terminal and Python Console windows. Or manually close and reopen those windows.
You have now created and activated an (ana)conda environment, and enabled it's use from within PyCharm. You should also now be able to ie. copy your code over to a fresh new file, and then hit ie. Ctrl+Shift+Less to run the file without having to manually set a configuration file for it.
Hope this helped!
Sources: source1, source2, source3
In my Experience I just opened PyCharm as administrator and the error was gone!
If you use PyCharm to create conda environment, you can choose conda environment not virtualenv.
When you get the error like "can't get the /path/to/", you can open PyCharm with administrator.
If you use "anaconda prompt" to create conda environment, you can use command line like conda create -n py36 python=3.6. Then you can activate environment using conda activate py36.

Prevent Visual Studio Code from activating the Python virtual environment

With a Python project opened, whenever I open the integrated terminal in Visual Studio Code it's automatically activating the virtual environment. I'm sure that's done by VS Code because I can find this command in the bash history of that terminal:
source <project-directory>/venv/bin/activate
I don't want the virtual environment to be activated. How can we prevent VS Code from doing that?
Add "python.terminal.activateEnvironment": false to your settings (globally to your user settings if you never want it, otherwise your settings.json file which is found in .vscode directory; this folder is found in your workspace directory if this is a per-workspace thing for you; docs).
If you open the vscode terminal first and then select python interpreter, then it won't activate the python environment. This answer works in vscode 1.44.0 with pyhton 3.8.1. I haven't tested with other versions. However, if you have any files or workspace open you need to close that first to close the python interpreter. You don't need to make any changes in settings.

Using linux console in pycharm

I'm new to pycharm, virtualenv, linux and git.
I've recently begun a journey of using djangoto make webapps. Before I used sublime to make scripts however now a more complex project management system such as pycarm was needed. I actually wanted to get a linux VM and go down that road but was advised that windows python IDE such as pycharm would be suitable
I recently learnt the importance of dependencies and how to use virtualenv. However in this tutorial, under the 'How do I use my shiny new virtual environment?' it starts using commands such as:
ls env
and
which python
Neither of which my pycharm console would understand.
I could use a console emulator such cmder to use the commands but then I would remove the convience of using the IDE's integrated one.
Should I upgrade to a linux VM ? Or can I install a package that allows me to use such commands in PyCharm.
As a bonus question, what are the commands in that tutorial ? are they linux commands? when ever i see $ .... is that the linux console ?
You can accomplish this using Vagrant: https://www.vagrantup.com/
You can use Vagrant and VirtualBox to setup a Linux VM (distro of your choice) and then install all of your Python dependencies in the VM. Once you have that setup, you can tell PyCharm to use the Python interpreter in your VM by following these steps:
Open the project settings dialog box in PyCharm.
Expand Project: (your project name) on the left side.
Click on Project Interpreter.
Click on the cog icon on the upper right side of the window and select Add Remote.
Click on the Vagrant radio button.
In the Vagrant Instance Folder box, select the directory your Vagrantfile is located in.
In the Vagrant Host URL box, make sure ssh://vagrant#127.0.0.1:2222 is specified.
Click OK.
Since Vagrant is compatible with Windows this solution should work for you. I have done it successfully using macOS and it works great. Good luck!
You might find this tutorial useful: https://developer.rackspace.com/blog/a-tutorial-on-application-development-using-vagrant-with-the-pycharm-ide/
I got this to work on Windows 10 with Anaconda Prompt. This terminal which comes with Anaconda, creates a "base" environment with a linux-like virtual machine and your Windows file system (C:\\) mounted to /c, and has bash installed with common Unix commands like cd, ls, chmod, echo, cat, ... Running programs from bash with access to environment variables is much nicer than Windows Powershell etc.
Now to get your Terminal in Pycharm to use Anaconda Prompt instead of cmd.exe, I followed this answer. After installing Anaconda and/or Anaconda Prompt, right-click -> Open File Location -> right-click the shortcut -> Properties -> copy file path. Then use your file path instead.
Conda is great for package environment management. Learn more about it here. For Django + Conda specifically, read here. You can also use pip to install from Python package indexes, github repos, and requirements.txt files instead. Unless you know how Anaconda Prompt works, I don't recommend creating your own environments from scratch. What worked for me was:
(base) C:\Users\wassadamo> conda create -n mynewenvironment --copy base
...
(base) C:\Users\wassadamo> conda activate mynewenvironment
(mynewenvironment) C:\Users\wassadamo> ls
folderA folderB file.txt
Works!
Whenever I try running conda deactivate to leave the base environment, my bash commands would stop working. So clone base as above.
Another tip: if you want to run shell scripts from Terminal within PyCharm with Anaconda Prompt this way, then execute them (e.g. "run.sh") on command line with
bash run.sh
I tried putting this on the first line of my run.sh
#!/usr/bin/bash
And running it with
./run.sh
But this had the effect of running it in an external Anaconda Prompt instance (add sleep, or some user input command to force it to wait and see for yourself). Explicitly running my .sh files with bash had the desired effect of running them in the same shell as I started them in PyCharm Terminal configured with Anaconda Prompt.

Categories

Resources