Batch equivalent of "source" on Windows: how to run a Python script from a virtualenv

Question:

I’ve done a fair bit of bash scripting, but very little batch scripting on Windows. I’m trying to activate a Python virtualenv, run a Python script, then deactivate the virtualenv when the script exits.

I’ve got a folder called env, which is my virtualenv, and a folder called work, which contains my scripts.

This is what I’ve got so far:

%~dp0envScriptsactivate.bat
python %~dp0workscript.py
deactivate

However, when I run the script, it activates the virtualenv then stops. It does not get to the second line and run the Python script. Is there a way to “source” the activate script folder, so that the rest of the batch script can be run as if I’d called activate.bat from the command line?

Asked By: jmite

||

Answers:

I’d say you just need to prepend ‘call’ to your activate.bat invocation, to ensure that the current batch file is resumed after activate is executed:

call %~dp0envScriptsactivate.bat

Consider doing the same for deactivate.bat. Furthermore, if you want to ensure that the current cmd.exe environment is not polluted by a call to your batch file, consider wrapping your commands in a setlocal/endlocal command pair.

Answered By: Nicola Musatti

I made a .lnk file that points to cmd /k "path/to the/script/activate.bat", and it works.

CMD parameters & options

Answered By: Maho

I suppose you just want to perform the same commands in Windows as if expected in Linux Bash/shell. When I want to start a virtualenv I am actually in its top directory, and the Linux command would be “source bin/activate”.

It is no problem to simulate this behaviour on Windows. Me personally, I’ve put a batch file named activate.bat somewhere on the PATH environment variable like this:

:: activate.bat
@echo off
REM source bin/activate
if "%1" == "bin/activate" (
    if not EXIST "%CD%Scriptsactivate.bat" goto notfound
    set WRAPEX=Scriptsactivate.bat
) ELSE (
       set WRAPEX=%*
)
call %WRAPEX%
goto :eof

:notfound
echo Cannot find the activate script -- aborting.
goto :eof
Answered By: newby2000