How to configure the VS Code shell like the developer command prompt? - shell

I'm trying to set up a task for compiling my C++ code in Visual Studio Code. I can't get it to work... but the command it spits out works perfectly fine when I just open the Developer Command Prompt and paste it in.
I've managed to narrow down this problem to the correct environment variables not being set in the shell that VS Code is using (as evidenced by running echo %INCLUDE% just returning %INCLUDE%).
Now I don't exactly know how the Developer Command Prompt differs from a normal Powershell terminal as used by VS Code, so I wouldn't know exactly how to configure it (aside from running vcvarsall.bat), but even if I could, every time I open a new terminal in VS Code the environment variables have reset themselves again.
In essence, the solutions to this problem that I can see are:
Run vcvarsall.bat before every build task.
Unfortunately I'm not familiar enough to know how to execute multiple commands in a row using a tasks.json configuration file.
Configure the shell that VS Code uses to be like the Developer Command Prompt by default.
Unfortunately, I have no clue where to even start with this. I can easily set the shell used to either cmd or PowerShell, but not to the Developer Command Prompt, and neither can I find where to configure its environment variables, nor do I know what the full effects of vcvarsall.bat are so I know which variables to set.
If there's a simpler way of achieving what I'm after, I'd be very happy to hear it. Though regardless, what it comes down to is that I want to know how to configure VS Code in a way that allows me to compile my code from inside the IDE.

I found an answer after a bunch more poking around. My setup (in tasks.json) is now as follows:
"command": "&",
"args": [
"'D:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Auxiliary\\Build\\vcvars32.bat';",
"cl.exe",
"/Zi",
"/EHsc",
"/Fe:",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"${file}"
]
with & you can execute a path that contains spaces. This leads to my vcvars32.bat (Location may be different for other people) which sets up the correct variables without having to enter them manually. ; lets you execute multiple commands one after the other in PowerShell.

The accepted answer did not work for me but was helpful in finding a solution that did work.
Using the task type "process" and then settting the command to the batch file called by the Developer Command Prompt launches the windows command prompt directly (instead of invoking it via powershell).
The first argument is then "&" which means that the compiler will be invoked within the developer command prompt context instead of just being passed to the batch file as an argument.
>{
"version": "2.0.0",
"tasks": [
{
"type": "process",
"label": "cl.exe build active file",
"command": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Auxiliary\\Build\\vcvars32.bat",
"args": [
"&"
"cl.exe",
"/Zi",
"/EHsc",
"/Fe:",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"${file}"
],
"problemMatcher": ["$msCompile"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

You can create a new task type within your tasks.json this way:
{
"version": "2.0.0",
"windows": {
"options": {
"shell": {
"executable": "cmd.exe",
"args": [
"/C",
// The path to VsDevCmd.bat depends on the version of Visual Studio you have installed.
"\"C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/Common7/Tools/VsDevCmd.bat\"",
"&&"
]
}
}
},
"tasks": [
{
"type": "shell",
"label": "cl.exe build active file",
"command": "cl.exe",
"args": [
"/Zi",
"/EHsc",
"/Fe:",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"${file}"
],
"problemMatcher": ["$msCompile"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
Don't forget to change type of task to "shell".
Note that the build will start with a couple of sec delay.
See here: https://code.visualstudio.com/docs/cpp/config-msvc#_run-vs-code-outside-the-developer-command-prompt

Related

How to set environment variables in vscode for debugging?

I have a fairly large python/c++ program that runs as follow:
. set_env.sh -option A -option B
python run.py
The set_env.sh script modifies the PYTHONPATH and does all sort of export in order to point to the right c++ program.
When running these two commands in the terminal, that works just well, however, using the debugger breaks it all.
I try running ". set_env.sh -option A -option B" in preLaunchTask but it seems the debugger can't see the new PYTHONPATH.
How can I make the debugger run the the set_env and consider the new PYTHONPATH ?
I had a similar problem and could solve it by setting environment variables in the "env" field of the launch.JSON file. This shoudl be stored in a .vscode folder in your project root, here is the docs: https://code.visualstudio.com/docs/python/debugging
I discovered the "env" field in this snippet here: https://gist.github.com/slaveofcode/b4c18efc99c16029913cde3fd2dba3ce
Not sure how to configure this dynamically with the -option A -option B however. Hope this helps :)
Inspired by my current area of work - which involved Python.
This is what I do for Flask.
MS Link
https://code.visualstudio.com/docs/python/debugging
For any regular Python debugging
Evidence
import os
for key in os.environ.keys():
print(f"{key}={os.environ.get(key)}")
After doing a F5 in VS Code with a file containing the above snippet:
Update on Feb 18
After receiving a comment I think the OP wants to run a script before debugging the Fask application. The steps that worked for me are below.
Overview
I ended up with the following files:
Add a PowerShell file dosomething.ps1 (my custom script which I intend to launch before every debug session)
Add a task.json (launch dosomething.ps1)
Edit the existing launch.json by linking it with the task in task.json
The file dosomething.ps1
Write-Host "Inside do something"
Write-Host "The value of the environment variable TEMP is $env:TEMPcls"
Write-Host "The current path of the script is $PSScriptroot"
The file tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "my script task",
"type": "shell",
"windows": {
"command": "pwsh -f dosomething.ps1"
},
"problemMatcher": []
}
]
}
Linking the launch.json with task.json
After pressing F5

How to change default terminal in VS Code

Whenever I open terminal in VS Code it always opens it's default one, and I always have to manually change it.
This is really annoying because I use terminal all the time every day. I checked Terminal settings in the toolbar but I can not find the option to change default. How can we do it?
When terminal is opened, in top right corner user should click on down-arrow button and then an option menu will appear. Then you should select Select Default Profile and you can choose your default terminal from there.
There are a lot of issues on github about this, see, e,g, Default console changed from what I wanted to Powershell during upgrade
( I think that is oldest tracking one for the v1.60 release).
I can replicate the problem on the Stable v1.60 build but not on the Insiders' Build with the exact same settings.
So it isn't your set-up and I'm sure the vscode team is aware of it. Your options are to
(1) use the Insiders' Build - at least that works for me,
(2) downgrade vscode to v1.59,
(3) when I click the Add Terminal + button I do get my default Git Bash terminal, or
(4) rename your default profile - see below.
FYI, my settings:
"terminal.integrated.profiles.windows": {
"PowerShell": {
"source": "PowerShell",
"icon": "terminal-powershell"
},
"Command Prompt": {
"path": [
"${env:windir}\\Sysnative\\cmd.exe",
"${env:windir}\\System32\\cmd.exe"
],
"args": [],
"icon": "terminal-cmd"
},
// "Git Bash": { // "Git Bash" does not work
"GitBash": { // "GitBash" does work
"path": "C:\\Program Files\\Git\\bin\\bash.exe",
"icon": "terminal-bash"
}
},
// "terminal.integrated.defaultProfile.windows": "Git Bash" // does not work for me
"terminal.integrated.defaultProfile.windows": "GitBash" // does work
// deprecated but may still work for you
// "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
Previously trying to set Git Bash as default profile, for Git Bash it was suggested to use GitBash instead (remove the space). That never worked for me until today in the v1.60 Stable Build.
So might try changing your profile name to something other than Git Bash or WSL, etc, if that isn't working.
I have attempted to set the default terminal about a dozen times, but it is not sticking with the latest update. It keeps opening PowerShell as the default terminal. These settings have been working fine for me until yesterday's update (v1.60.0), which broke this.
"terminal.integrated.defaultProfile.windows": "WSL",
"terminal.integrated.profiles.windows": {
"WSL": {
"path": "C:\\WINDOWS\\System32\\wsl.exe",
"args": [
"~"
],
"icon": "terminal-ubuntu"
},
"Git Bash": {
"source": "Git Bash",
"icon": "terminal-bash"
},
"Command Prompt": {
"path": [
"${env:windir}\\System32\\cmd.exe"
],
"args": ["/K cls && cd /D C:\\OD"],
"icon": "terminal-cmd"
},
"PowerShell": {
"source": "PowerShell",
"icon": "terminal-powershell"
}
}
Anyone else experiencing this?
The solution that worked for me is:
Method 1:
Open Settings.json file and add the following line of code
"terminal.integrated.defaultProfile.windows": "Command Prompt"
After making this change my Settings.json file looks like this:
{
"files.autoSave": "afterDelay",
"window.zoomLevel": 1,
"liveServer.settings.donotVerifyTags": true,
"liveServer.settings.donotShowInfoMsg": true,
"terminal.integrated.automationShell.windows": "",
"terminal.integrated.automationShell.linux": "",
"terminal.integrated.defaultProfile.windows": "Command Prompt"
}
Method 2:
Click on Settings and search for defaultprofilewindows
You will get the default terminal on this tab. Click on the menu list and select Command Prompt.
You can choose any of the available Terminals and check which one will work as you want.
Note: Using either method you will get the same results. Both of these above-mentioned methods are working perfectly for me.
I got it to load properly, but when I try to run a Python script using the run button, it runs in PowerShell.
"terminal.integrated.automationShell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
"terminal.external.windowsExec": "C:\\Program Files\\Git\\bin\\bash.exe",
"terminal.integrated.profiles.windows": {
"PowerShell": null,
"Command Prompt": null,
"Git Bash": {
"path": "C:\\Program Files\\Git\\bin\\bash.exe",
"icon": "terminal-bash"
},
},
"terminal.integrated.defaultProfile.windows": "Git Bash"

How do I create custom terminal commands in VS Code and assign key bindings to these commands?

Please don't flag as duplicate without reading. Seriously not able to find this information anywhere.
I work on projects that make use of "Make". Right now I have to type every make command in the integrated terminal like "make all", "make clean" etc. I'd like to have some keyboard shortcuts that do the work, similar to how default build tasks have one.
I tried command runner extensions but they too have very vague info on how to make these custom commands. Been fiddling around with settings and keybindings json file for few days now. I'm not a web developer so don't know much about working with json files to begin with and configure stuff observing the default templates.
All I find is the default template of
{
key : " ",
command : " "
}
Tried fiddling with this on keybindings.json file but my command is not found.
Any help on this would be much appreciated.
With the command workbench.action.terminal.sendSequence you can send text to the terminal
An example key binding
{
"key": "ctrl+f5", // or any other combo
"command": "workbench.action.terminal.sendSequence",
"args": { "text": "make all\u000D" }
}
Be sure the terminal is at a directory where the command works, or add a cd command in front, you can use variables (credit to Mark for the correction).
If you define multiple tasks to do the stuff you can execute the task with a keybinding
{
"key": "shift+f5", // or any other combo
"command": "workbench.action.tasks.runTask",
"args": "Name_of_task"
}
In the task you can use variables.

VSCode Change Default Terminal

I am using Visual Studio Code on my Windows 10 PC. I want to change my default terminal from Windows PowerShell to Bash on Ubuntu (on Windows).
How can I do that?
You can also select your default terminal by pressing F1 in VS Code and typing/selecting Terminal: Select Default Profile (or Terminal: Select Default Shell in older VSCode versions).
Older:
Configure your default integrated terminal by running the Terminal: Select Default Profile command, which is also accessible via the terminal dropdown.
See https://code.visualstudio.com/docs/editor/integrated-terminal#_terminal-profiles
I just type following keywords in the opened terminal;
powershell
bash
cmd
node
python (or python3)
See details in the below image. (VSCode version 1.19.1 - windows 10 OS)
It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)
Go to File > Preferences > Settings (or press Ctrl+,) then click the leftmost icon in the top right corner, "Open Settings (JSON)"
In the JSON settings window, add this (within the curly braces {}):
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\bash.exe"`
(Here you can put any other custom settings you want as well)
Checkout that path to make sure your bash.exe file is there otherwise find out where it is and point to that path instead.
Now if you open a new terminal window in VS Code, it should open with bash instead of PowerShell.
Since you use WSL, VSCode has dedicated Remote - WSL extension so you can use Linux environment directly in VSCode. When you open the project inside Linux, by default, it's use Linux default shell (bash by default), so no config needed.
If you want to switch to other profile, there is Terminal > Integrated > Default Profile: Linux section so you can pick your favorite one.
Going off of #arielhad's solution...
My VSCode version was 1.57.1.
Open settings.xml file:
Ctrl + Shift + p
Type 'Open Settings (JSON)' and select.
Add the following:
"terminal.integrated.profiles.windows": {
"PowerShell": {
"path": [
"${env:windir}\\Sysnative\\WindowsPowerShell\\v1.0\\powershell.exe",
"${env:windir}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
],
"source": "PowerShell",
"icon": "terminal-powershell",
"args": [
"-NoLogo",
"-ExecutionPolicy",
"Bypass"
]
},
"Command Prompt": {
"path": [
"${env:windir}\\Sysnative\\cmd.exe",
"${env:windir}\\System32\\cmd.exe"
],
"icon": "terminal-cmd"
},
//START: THIS DOES NOT WORK
"Git Bash": {
"path": [
"C:\\Program Files\\Git\\bin\\bash.exe",
],
"source": "Git Bash",
"icon": "terminal-bash"
}
// END: THIS DOES NOT WORK
//START: THIS WORKS
"GitBash": {
"path": [
"C:\\Program Files\\Git\\bin\\bash.exe",
],
"icon": "terminal-bash"
}
// END: THIS WORKS
}
I don't know why the second way works but it does. It appears the 'Git Bash' is a reserved name and I guess you cannot set the path.
To change the default terminal for your project in Visual Studio Code:
Create a folder by name of .vscode
Create a settings.json file in this folder:
Write the settings you want
for example, if you are a window user and want to set "Command Prompt" as the default terminal you can write:
"terminal.integrated.defaultProfile.windows": "Command Prompt"
values You can pass: "Git Bash", "PowerShell", and "Command Prompt".
for Linux you will use terminal.integrated.defaultProfile.linux and for mac os you will use: terminal.integrated.defaultProfile.osx
press ctrl+Shift+p
-> type settings.json
at the of file change the 'powershell' to 'Git Bash'
The integrated shell option still works but has been depreciated. The fix is to use the integrated profile instead:
"terminal.integrated.defaultProfile.windows": "C:\\Program Files\\Git\\bin\\bash.exe (migrated)",
"terminal.integrated.profiles.windows": {
"C:\\Program Files\\Git\\bin\\bash.exe (migrated)": {
"path": "C:\\Program Files\\Git\\bin\\bash.exe",
"args": []
}
}
Just press Ctrl + Shift +p
search "Terminal: Select Default Profile" click
You will see terminals options and select Git Bash
If you want to select the type of console, you can write this in the file "keybinding.json" (this file can be found in the following path "File-> Preferences-> Keyboard Shortcuts")
`
//with this you can select what type of console you want
{
"key": "ctrl+shift+t",
"command": "shellLauncher.launch"
},
//and this will help you quickly change console
{
"key": "ctrl+shift+j",
"command": "workbench.action.terminal.focusNext"
},
{
"key": "ctrl+shift+k",
"command": "workbench.action.terminal.focusPrevious"
}`
You can change the terminal by opening command pallete by pressing CTRL SHIFT P
or you can go to View in the top and click "Open Command Pallete"
then type Terminal: Select Default Profile
and you you type which terminal you want.

How can I launch an exe within a conda env

I'm using vscode in Windows 10 as my code editor, and want to make an easy way to launch it with the correct conda env to allow debugging.
Currently I am having to open a command prompt, then activate the conda env, then paste the shortcut to vscode into the prompt to execute. Like so:
cmd
activate env-name
"C:\Program Files (x86)\Microsoft VS Code\Code.exe"
I have tried creating a batch file to wrap these calls, but unfortunately once I call "source activate" to start the conda env, the batch commands after this are not executed as it is considered another instance.
Any tips? Other than writing a vscode extension to handle this (which I'm seriously tempted to do, but it's such a simple problem...)
You might want to run source activate env-name as a task in visual studio.
https://code.visualstudio.com/Docs/editor/tasks
tasks.json
{
"version": "0.1.0",
"command": "cmd",
"isShellCommand": true,
"suppressTaskName": true,
"args": [],
"tasks": [
{
"taskName": "development",
"args": ["source", "activate", "env-name"]
}
]
}
The best option I found is to set the python.venvPath parameter in vscode settings to your anaconda envs folder.
"python.venvPath": "/Users/[...]/Anaconda3/envs"
Then if you bring up the command palette (ctl + shift + P on windows/linux, cmd + shift + P on mac) and type Python: Select Workspace Interpreter all your envs will show up and you can select which env to use.
The python extension will also need to be installed for the Select Workspace Interpreter option.
Note: The Select Workspace Interpreter takes around 10 seconds to come up on my computer using the current version of VSCode. My answer was originally posted here.
Using Conda 4.7.5, I was able to change the Target under the VsCode taskbar shortcut Properties from:
"C:\Users\Paul.siersma\AppData\Local\Programs\Microsoft VS Code\Code.exe"
To:
C:\Users\Paul.siersma\Anaconda3\_conda.exe run -p C:\Users\Paul.siersma\Anaconda3 "C:\Users\Paul.siersma\AppData\Local\Programs\Microsoft VS Code\Code.exe"
This uses the run command (marked experimental) and starts VSCode using the base Conda environment. You could specify another environment by changing the -p flag to the environment location eg -p [..]\Anaconda3\envs\myenv

Resources