How to activate virtual environment in Vscode when running scripts are disabled in system?

Question:

I created a virtual environment in vscode in a folder called server by typing:

python -m venv env 

And I opened the server folder, select interpreter Python 3.8.1 64-bit(‘env’:venv)

then I got following error:

enter image description here

I can’t find any solution to this and I am stuck for hours.

Asked By: bdemirka

||

Answers:

It seems that it is going to activate the environment through a powershell script. And running such scripts is turned off by default. Also, usually a virtual environment is activated through cmd and .bat script. You could either turn on running powershell script or make VS Code activate an environment through cmd and .bat file.

The first way – using cmd instead of Powershell

I just checked it in my PC and VS Code doesn’t use Powershell at all. It activate an environment with cmd instead of Powershell. Probably it is worth to check VS Code settings, set cmd as a default terminal. It is probably such an option in the main settings.json (you can open it through ctrl+shift+p and type ‘open settings (JSON)’): "terminal.integrated.shell.windows": "C:\Windows\System32\cmd.exe",.

The second way – changing Powershell execution policy

In order to change Powershell execution policy you can add "terminal.integrated.shellArgs.windows": ["-ExecutionPolicy", "Bypass"] to your main VS Code settings.
Also you can open a Powershell window as administrator and type the following:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Then respond y to any questions.

Answered By: I_Can_Help

An update with regards to using the Command Prompt instead of Powershell in VS Code:

When implementing "terminal.integrated.shell.windows": "C:\Windows\System32\cmd.exe" in settings.json it gives the notice:

This is deprecated, the new recommended way to configure your default shell is by creating a terminal profile in #terminal.integrated.profiles.windows# and setting its profile name as the default in #terminal.integrated.defaultProfile.windows#. This will currently take priority over the new profiles settings but that will change in the future

After taking a look at the documentation I’ve found that the correct alternative would be to include a line as shown below.

"terminal.integrated.defaultProfile.windows": "Command Prompt"

Alternatively, you can also use the GUI as shown in the documentation. More advanced settings are also shown there.

Answered By: Seth