Search code examples
pythonvisual-studio-codevirtual-environment

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


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.


Solution

  • 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.