Activating Python Virtual env in Batch file

Question:

I’m trying to make a batch script (called run_windows) that check if the python virtual environment exists and if not, create it then activate it, install the requirements and finally run some python code.

set "VIRTUAL_ENV=mat_visualizer_env"

:read_mat
%VIRTUAL_ENV%Scriptsactivate
pip install -r app_files/requirements.txt
python -c "import sys; sys.path.insert(1,'app_files'); from main import visualize_mat_eeg; visualize_mat_eeg('%1')"
pause
EXIT /B 0

IF EXIST "%VIRTUAL_ENV%Scriptsactivate.bat" (
    CALL :read_mat
) ELSE (
    pip install virtualenv
    python -m venv mat_visualizer_env
    CALL :read_mat
)

However, when I run my script, the code exits at line 4: %VIRTUAL_ENV%Scriptsactivate with no errors:

enter image description here

Asked By: Fabio Magarelli

||

Answers:

Few things:

  • Running the .bat or bash version of activate in is not predictable, Activate.ps1 is found in newer releases. It could probably be used with older versions if copied from a newer release.
  • Scripts in windows (.bat or .cmd in windows) processes from top down, :<ANCHOR> is not skipped like a Sub or Function would be.

I have only worked with the Conda version of activate.ps1 and it adds some nice commands. Had a quick look in standard Python 3.10.5 and it does not add commands but should work fine.

Edit: Added that while working, is not the best option to use the bash version of activate

Answered By: DaSe

Here is a quick example of your batch file rearranged, and using the Call command as previously instructed.

@Echo Off

Set "VIRTUAL_ENV=mat_visualizer_env"

If Not Exist "%VIRTUAL_ENV%Scriptsactivate.bat" (
    pip.exe install virtualenv
    python.exe -m venv %VIRTUAL_ENV%
)

If Not Exist "%VIRTUAL_ENV%Scriptsactivate.bat" Exit /B 1

Call "%VIRTUAL_ENV%Scriptsactivate.bat"
pip.exe install -r app_files/requirements.txt
python.exe -c "import sys; sys.path.insert(1,'app_files'); from main import visualize_mat_eeg; visualize_mat_eeg('%~1')"

Pause
Exit /B 0

Please note, that there is no working directory defined in this script, as was yours, and therefore no way to guarantee that when run, the relative paths point to the intended locations. Additionally, you have not made it clear what %1 was supposed to be, or where it was coming from, so I cannot guarantee whether that is correct.

Answered By: Compo