VSCode integrated terminal doesn't use Conda environment to execute python files - python

[Mac OS] Up until yesterday, my python files were executing with whatever environment I had activated. After that, I explored python debugging and how it could be used with the Conda environment. It worked like a charm.
Today, I got a notification in VSC saying something along the lines of "python.PythonPath in settings.json ... default...". Because I was in a hurry, I didn't pay attention to it. Now, when I activate conda environment X, it shows up in the terminal that X is activated, when I use "conda list" it lists the correct modules installed in X, and in VSC's status bar, it shows that I am using X too.
Unfortunately, when I go running the python code, it simply uses "python - u ", and that does not happen to be X.
Could someone please tell me what's wrong? If there's some information that I haven't provided, please feel free to let me know about it and I'll update the question accordingly.

Do you mean the VSCode works like the first picture and you want it can run in the terminal like the second picture?
The first picture was running by Code Runner, the second picture was running by Python Extension. You can choose it like this:
If I am misunderstanding your problem, please point it out and provide the related info.

You can modify settings.json to use the specific conda environment python interpreter. Or you can set the interpreter manually. \
Writing settings.json:
add the line in settings.json :
"python.pythonPath": "/home/python36/python", // the path of python
// interpreter in your desired conda environment.
Or In the editor to the bottom left corner, you should see something like below
Click it, you should see a prompt opening above, like
Select the interpreter and you're good to go.

Related

Problems installing Python packages into a virtual environment in Visual Studio Code

Although I'm enjoying developing in Python in Visual Code, I'm finding managing virtual environments and packages frustrating, and particularly am struggling with installing packages in the right place. Here's my sequence of steps, and the problem I then have - I wonder if anyone could kindly tell me where I've gone wrong? Or do I really need to include the full Python path?
So first I create a new virtual environment:
I can see that this works:
I then choose to use the Python interpreter in this new virtual environment (I can't quite see why I have to do this - surely this should happen as part of the activation process - but I can live with it):
At the bottom left corner of my screen, I get the reassuring fact that I'm using the right Python interpreter:
I then install a package (I've chosen requests more or less at random):
However, this is going in my default Python location. To get it in my new virtual environment, I seem to have to include the full path to the Python interpreter:
This can't be right, although it does work - I can now see the installed package:
Can anyone help please?
Personally I haven't had luck using PowerShell (due to permissions to run PowerShell scripts) so I use Command Prompt in VS Code instead.
For PowerShell, perhaps activating your environment using Scripts\activate.ps1 will work instead. From the docs at:
https://docs.python.org/3/library/venv.html
# PS C:\> <venv>\Scripts\Activate.ps1
StackOverflowExample\Scripts\Activate.ps1
It is a bit confusing in VSCode having an interpreter selected and a different Command Prompt/Power Shell terminal used to install packages into a virtual environment.
Another confusing point is running StackOverflowExample\Scripts\activate doesn't suggest you are doing anything is wrong.
I agree with Jason Cook. activate.bat used to activate the environment in Cmd, you should take Activate.ps1 instead of activate.bat.
But you need not activate the environment by yourself. The Python extension can choose the right one to activate the environment for you when you create a new terminal.
After you select the interpreter, you need to create a new terminal. In general, we take a shortcut of Ctrl+Shift+`.
And if you want to turn off this function, you can set this in the settings.json:
"python.terminal.activateEnvironment": false,
OK, thanks to Jason/Steven I have finally got the hang of what you should be simple, but isn't. Here's what I reckon is the easiest way to create and activate a Python virtual environment in Visual Studio code. Let's say I start with the Tutorial environment active, and want to create one called ForeignHoliday (we can but dream). Start by creating the new environment in the VS Code terminal:
This creates the environment:
However, it doesn't activate it, nor does it change the default Python interpreter to use the one for the new virtual environment. You can do both of these things in one go by choosing an interpreter - click here at the bottom left of the VS Code screen:
You can now select an interpreter - your new virtual environment (irritatingly) won't be listed yet, so you'll have to find it:
Choose to find your interpreter:
Double-click on the Python interpreter in the Scripts folder in your new virtual environment (the pythonw alternative doesn't invoke a terminal window, so most people should avoid this - see this SO article):
Now press SHIFT + CTRL + ' to start a new terminal window (NOT just CTRL + ', as this switches you to an existing terminal window). You should see this:
You can now install and import packages and they will all be in the right place! I wish I'd read this answer a few days ago ...

Can't import Python modules after transferring to VSCode from PyCharm

My basic issue is that I get an error whenever I try to import a Python module in VSCode, which doesn't happen when using PyCharm.
From what I've read so far the problem seems to be with the python path, or the interpreter.
My issue is, that I don't really understand what the issue is, meaning I quickly feel lost when trying to apply some of the other solutions I have found, because I don't know what to look for.
Can someone clarify what is going wrong and how to fix it?
Edit: I probably forgot to add a crucial detail. I was facing this issue when running my python files using the code runner.
This is what I needed to add to my settings.json in order to get everything working completely:
"code-runner.executorMap": {
"python": "$enterPythonPathhere"
}
In VS Code press Ctrl+Shift+P
Type select interpreter in the search box
Python: Select Interpreter
This will show a couple of environment paths. Click on the environment you were using in pycharm.
If your pycharm environment does show on the list you should enter the environment path instead. That should work.
For installing and using python modules in VS Code, please refer to the following:
As people mentioned, select the desired python environment in the lower left corner of VS Code.
Please use the shortcut key Ctrl+Shift+` to open a new VS Code terminal, and then check whether it has entered the selected python environment.("python --version" or "pip --version")
Install the module.
Check the installation of the module.(pip show module_name)
Reference: Python environments in VS Code.

VScode extensions: CODE RUNNER and PYTHON PREVIEWER do not use the interpreter I select

I'm using some VSCODE extensions that I find really interesting, those are: Python Preview (https://github.com/dongli0x00/python-preview), and Code Runner (https://github.com/formulahendry/vscode-code-runner.git).
I normally let VScode select the environment for python development and it is so good, it always chooses the right one:
So the Problem here is, that, as you can see, in the code I'm using MatPlotLib and NumPy modules. And when I use either Python Preview or Code Runner, they do not detect the right interpreter, I don't know if they follow the interpreter that VScode selects automatically or if some configuration is needed in order for them to do it.
These are the captures of both extensions selecting the wrong interpreter:
PYTHON PREVIEW:
CODE RUNNER:
Well I'd just like to know if this happens due to the extensions configuration and if I can solve it somehow :)
Thanks.
Code Runner allows you to point to an interpreter as follows:
Search Settings for “executor map” and click “edit in settings.json”
Paste in this line:
"python": "$pythonPath -u $fullFileName",
So that the entire file looks like this:
{
...
"code-runner.executorMap": {
"python": "$pythonPath -u $fullFileName",
}
...
}
This way Code Runner uses the interpreter you have set in “Python Path”. (Search that in your settings.)
The Code Runner README contains other variables you may use in code-runner.executorMap, in case your Python executable is located someplace else.
PS You might also want to add interpreters for other languages, if you use any.
This is not a fix, but a workaround.
I had the same issue as you have.
I tried many methods mentioned in variour blogs as well as stackoverflow, but it seems it wont fix the issue.
Then I removed Python2 completely from my system, as I don't use Py2 for anything, to make it working.
I recommend you to remove Python2 if you dont use that.
This will fix your issue
Tried and Tested
I created a virtual environment and when i clicked the option Python: Run Current File in Python Interactive Window, the environment was activated automatically like the following screenshot shows:
However, pressing Ctrl+Shift+P to open the panel and select the option: Terminal: Create New Integrated Terminal is used more often to activate the virtual environment.
So check if you can get the above output which means you activate the virtual env successfully by pressing Ctrl+Shift+`, which is the shortcut key of creating new integrated terminal. If the environment is still not activated, press Ctrl+, to open settings.json and add
"python.terminal.activateEnvironment": true
Reference: python environment. Try this and see if the problem goes away.

VS Code doesn't recognize Python Virtual Environment Packages - It shows red underlines

I installed python virtual env. I use vs code. I imported scrapy in my code and vs code doesn't recognize the module. Actually, it works well when I run it. scrapy crawl tester
Just, vs code shows red underlines that mean "Unable to import scrapy" So this is just vs code issue, not venv or scrapy package install issue.
This code works well and actuallay, scrapy is imported without any issue. This is just vs code issue. Thank you.
You might be able to solve your problem by using CTRL+Shift+P to add "Python: Select Interpreter" to your project.
If you created a virtual environment and activated it as well
type which python on macOS/Linux,
type where python on Windows,
inside the activated terminal session.
(env) userpc#pc:~$ which python
/home/userpc/Desktop/foldername/env/bin/python
In VSCode press Ctrl+Shift+P, under >Select Interpreter paste the location you receive using the former command.
Once done, restart VSCode.
VSCode will also ask you to install pylint in your environment and if it doesn't you can do the same by activating you environment and typing
pip install pylint
inside the activated terminal session.
Ran into the same problem - selected the correct Python interpreter in VS Code, pip installed all the desired Python libraries but import is still underlined in VS Code.
What you need to do
What worked for me is to make sure that the linter that you are using in this VS Code instance (I was using pylint) is from the bin folder of the virtual environment, not somewhere else.
How you can do it
I'll use the absolute path to the desired virtual environment /User/ProjectFolder/env as an example.
To check that you meet the conditions stated in What you need to do, toggle the settings.json file in VS Code by pressing ⌘ + ,:
Make sure that the correct Python interpreter is selected. i.e. "python.pythonPath":/User/ProjectFolder/env/bin/python3.
Make sure that the linter (e.g. pylint) is located in that bin folder, not anywhere else. i.e "python.linting.pylintPath":/User/ProjectFolder/env/bin/pylint, NOT something like "python.linting.pylintPath":/usr/local/bin/pylint.
This means that you have to install your desired linter in the virtual environment.
Hope this helps.
I tried #cleon-w's answer which worked for me. (Thanks Cleon)
I was using pyenv on my Mac M1 (Big Sur) with vscode. vscode could not resolve the
paths to python that the pyenv provides, so I looked within the pyenv scripts to find the absolute paths
to the underlying python and the pylint files.
As #Cleon W says I ensured pylint and python are in the same bin directory.
Then edit VS Code settings.json to point to them directly (bypass .pyenv) and the imports could be found.
settings.json (vscode)
"python.defaultInterpreterPath": "/Users/USERNAME/.pyenv/shims/python",
"python.pythonPath": "/Users/USERNAME/.pyenv/versions/3.9.1/bin/python",
I have similar problem with Django. What solved my problem was:
create .vscode/settings.json file inside root dir for project.
add this json {"python.defaultInterpreterPath": "path to bin directory in root dir for project"}
Ctrl-Shif-P -> Python: Select Interpreter -> select one that said: Use Python from python.defaultInterpreterPath. If it's not in the list, hit refresh (circled refresh button on the top of settings box).

VSCode / Virtual Studio Code: Unable to Load Conda Environment in VSCode Terminal

I'm attempting to switch to VScode, to use the built-in terminal to interact with Anaconda, and know VScode supports Anaconda because it ships with Anaconda.
From the documentation, and various tutorials/videos, I see that the conda/virtual environments are recognized (seemingly natively). And yet I cannot seem to figure it out.
With the python script I want to run open in VScode, I ensure that I am using the correct interpreter/environment as follows:
ctrl+shift+p to load Command Pallette
Python:Select Interpreter
C:...\Anaconda3\envs\p3audio\python.exe
At the bottom of the window, the environment also appears to be pointing to the environment as I loaded the p3audio environment to use python 3.7 and this is what is showing ('Anaconda Python 3.7.0') (The top Python in top level anaconda is shipped with 3.6 I believe)
When I try to run the python file by 'Run Active File' from the Terminal Menu, it automatically loads powershell and executes this into the terminal:
PS C:...\Anaconda3\envs> c:...\Anaconda3\envs\Projects\p3audo_projects\my_script.py
(the second path is in yellow)
If I try to activate the conda environment manually from the powershell terminal, it doesn't recognize it.
I can run the script fine from the anaconda prompt terminal.
I think it may be a path issue, but all of the documentation/resources I used suggest I shouldn't have the issue if I didn't select (tick the box) for add path on install. I checked my environment variable path and don't have anaconda on it.
I am wondering if it has to do with the 'you can change the default terminal shell by selecting the customize button' that loads in the terminal window. This leads me to believe that I have to manually add the conda terminal path somewhere. But this surprises me because, vscode shipped with anaconda, and I see no mention of this in the documentation.
I am obviously a newbie at this, and have suffered through environment variable/path issues many times. But I can't figure this out.
Any help would be greatly appreciated.
Thanks
For anyone struggling with this, I'll tell you what worked for me. This was after four hours of trying to get Python to run in PyCharm and VS Code.
Basically dldatacowboy has the answer, but the argument for terminal.integrated.shellArgs.windows needs to be reformatted (maybe only if you're on a Windows machine?). There should be no space before the "K", and the backspaces need to be double backspaces. So my settings in my settings.json file look like so:
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\cmd.exe",
"terminal.integrated.shellArgs.windows": ["/K","C:\\ProgramData\\Anaconda3\\Scripts\\activate.bat C:\\ProgramData\\Anaconda3"]
Make sure to change the path to whatever comes up when you follow dldatacowboy, but then change the backslashes to double backslashes.
For people working in Mac OS.
In order to setup the integrated terminal in VS Code to use the active Anaconda Environment's Python by default, you will need to modify your User or Workspace Setting's 'settings.json' with the following line:
"terminal.integrated.shellArgs.osx": [],
For reference: this closed issue addressed the topic.
Ok I figured it out. VSCode is awesome.
Go to Settings (ctrl+,)
Decide if you want this custom terminal to be applied at the User Settings or Workspace Settings, and select that (located just below the settings search bar)
Open settings.json (don't know shortcut key yet, it is the three-dot menu located to the far right on the same row as the User Settings and Workspace Settings tabs.
Locate "terminal.integrated.shell.windows" in the Default User Settings (left panel), again you can enter it into the search bar to locate it.
Copy it over to the User Settings/Workspace Settings (depending on what you selected or now decide to select) (in the right panel)
e.g. copy:
"terminal.integrated.shell.windows": "C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe",into json array on the right
Edit the path to equal your cmd executable path
e.g. "terminal.integrated.shell.windows":
"C:\Windows\System32\cmd.exe",
You need to create the argument, which is what I was confused about:
Go to start menu in windows, locate the Anaconda Prompt Open File Location with right click, inspect properties and see Target Location Path. Don't worry about the first string, copy from after the cmd.exe to the end. Use this for the "terminal.integrated.shellArgs.windows"
e.g. "terminal.integrated.shellArgs.windows": [
"/K", "C:\Users\User-1\Anaconda3\Scripts\activate.bat C:\Users\User-1\Anaconda3"
Make sure you separate with a comma and properly contain strings with all four quotations. Save Close vscode. load it up and you are good to go.
Hope this helps someone! = )
With the recent conda release (4.6.1) Conda can now be initialized in Powershell and can now be integrated in VSCode cleanly. I made a stackoverflow post here
Please use the following settings in vs code and it ought to work, provided your conda is installed appropriately. Also, please make modifications according to your environment.
settings for powershell is mentioned below
{
"workbench.startupEditor": "newUntitledFile",
"editor.wordWrap": "on",
"editor.wordWrapColumn": 100,
"terminal.integrated.shell.windows": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
"terminal.integrated.shellArgs.windows": [
"-ExecutionPolicy", "ByPass", "-NoExit", "-Command", "&",
"'C:\\Users\\kpache\\Anaconda3\\shell\\condabin\\conda-hook.ps1' ; conda activate 'C:\\Users\\kpache\\Anaconda3'"
// "/K", "C:\\Users\\kpache\\Anaconda3\\Scripts\\activate.bat", "C:\\Users\\kpache\\Anaconda3"
],
"terminal.external.windowsExec": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
"workbench.colorTheme": "Default Light+"
}
It looks like you've been mislead by the title of this article.
If you read the article, it says Anaconda comes with Visual Studio Code included. So it would be easier to setup if you download and install the Anaconda setup.
If you look at the article above, it shows in one of the installation steps, the option to install VS Code.
The following is the download link:
Sharing what worked for me on MacOS.
For latest versions of Anaconda (v 2019.10 at the time of this writing) add this line to your .bash_profile:
export PATH="/opt/anaconda3/bin:$PATH"
And for older versions it may look like:
export PATH="/anaconda3/bin:$PATH"
Hope that helps someone.

Categories

Resources