Search code examples
python-3.xpowershellpython-venv

How to activate a file using powershell functions (related to python)?


I want to create a venv (virtual environment) using this python command in windows 10

python -m venv "environment name"

and to activate it I have to enter this line in powershell

"environment name"\scripts\activate or "environment name"\scripts\activate.bat

so I created a this function in $profile

function active {
    param (
        $venv_name = "venv"
    )
    
    "$($venv_name)\scripts\activate.bat"
}

but the problem is this function only shows the path and nothing more but I want it to activate

"environment name"\scripts\activate.bat

How can I fix this ?

and it doesn't have to be function


Solution

  • Use the invocation operator &:

    function active {
        param (
            $venv_name = "venv"
        )
        
        & "$($venv_name)\scripts\activate.bat"
    }
    

    You can also simplify the string slightly, $() is not required for simple variable expansion:

    & "${venv_name}\scripts\activate.bat"