Home > Net >  How to activate an environment using PowerShell from any directory in one single command?
How to activate an environment using PowerShell from any directory in one single command?

Time:06-06

I want to activate a python 3.8 environment without having to 'cd' to my environment's path in windows 10. If I use commands like path/to/my/env/Scripts/activate or path/to/my/env/Scripts/activate.bat does not activate my environment. To activate my environment I am forced to use two commands -

  1. cd path\to\my\env\Scripts\
  2. ./activate
  3. cd back\to\my\project\dir

I don't want to change my current project working directory every time to activate the environment in windows 10 powershell. In Linux i can use 1 single source path/to/my/env/bin command. It allows me to stay in my current project directory and activate the environment using its path address. How can achieve similar in windows 10, activating a python environment with 1 single command?

enter image description here

In above picture I get green colored name of my environment once it is successfully activated.

CodePudding user response:

Running something like this from PowerShell:

C:\Users\Admin\Desktop\pyenv\Scripts\activate.bat

It works, but doesn't have the effect you expect. Running a batch file from PowerShell will launch a new instance of cmd, which will get the activated environment - but once the batch file completes, the cmd process is done and will be terminated, taking the modified environment variables with it.

You could write a batch file like this and it would work (from both Command Prompt and PowerShell) as expected:

call C:\Users\Admin\Desktop\pyenv\Scripts\activate.bat
python myscript.py

It would run myscript.py in the intended environment.

Running just the batch file activation command (with path) from a running Command Prompt works in a way that you probably expected to work in PowerShell as well. It modifies the current environment and allows you to interactively run commands in it afterwards, until you deactivate.

However, if you want to change the current environment on the current PowerShell prompt, you need to run (this is the answer):

C:\Users\Admin\Desktop\pyenv\Scripts\activate.ps1

i.e. run the .ps1 PowerShell script, don't run the .bat Command Prompt script.

Note: something that may cause this confusion is that Windows Commmand Prompt automatically runs script.bat if the script command is entered (and there are no other script.___ files that have an extension that comes before .bat in the PATHEXT variable); however, PowerShell finds the script (no extension) file and settles for that. You can see that this is the case by running:

Get-Command C:\Users\Admin\Desktop\pyenv\Scripts\activate

PowerShell does also use PATHEXT, but matches the filename without extension before it and that file is there (it's the Bash script):

Write-Host $env:PATHEXT

(more on PowerShell's use of environment variables here)

  • Related