Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

%~dp0env\Scripts\activate.bat python %~dp0work\script.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?

like image 235
jmite Avatar asked Jul 21 '11 19:07

jmite


People also ask

How do I run a Python script in virtual environment Windows?

In "Program/script" textbox you set the path to Python executable (in my case is inside the virtualenv folder). "Add arguments" => Just the name of your Python script (name. ppy). "Start in" => The full path of your Python script (without the name.py).

How do I run a Python script in a virtual environment?

To use the virtual environment you created to run Python scripts, simply invoke Python from the command line in the context where you activated it. For instance, to run a script, just run python myscript.py .


2 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 %~dp0env\Scripts\activate.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.

like image 62
Nicola Musatti Avatar answered Sep 20 '22 23:09

Nicola Musatti


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

CMD parameters & options

like image 21
Maho Avatar answered Sep 19 '22 23:09

Maho