Home > front end >  Activating Python Virtual env in Batch file
Activating Python Virtual env in Batch file

Time:08-30

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%\Scripts\activate
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%\Scripts\activate.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%\Scripts\activate with no errors:

enter image description here

CodePudding user response:

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

  • Related