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?
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.
I made a .lnk file that points to cmd /k "path/to the/script/activate.bat", and it works.
CMD parameters & options
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%\Scripts\activate.bat" goto notfound
set WRAPEX=Scripts\activate.bat
) ELSE (
set WRAPEX=%*
)
call %WRAPEX%
goto :eof
:notfound
echo Cannot find the activate script -- aborting.
goto :eof
Related
I want to run a python file to a windows computer that uses packages installed with miniconda with one double-click (this is very inmportant).
The computer that I will run it, does not have anything installed (you can think of it as a formatted pc).
I figured out to do it with .bat file and it works, but I have to run the file twice, since the first time after installing miniconda, the shell needs to restart. I searched but I did not find a command to restart the shell and continue with the execution of the python file in order to be done with just one double-click. So, only for the first time, it has to be done manually.
Is there a way to do it with a batch file or should I do it otherwise?
Here is my batch file
START %CD%\Miniconda3-latest-Windows-x86_64.exe /InstallationType=JustMe /AddToPath=1 /RegisterPython=0 /S /D=%CD%\miniconda3
CALL conda activate .\envs_dir
python python_script.py
PAUSE
The problem was that the installation changes the user environment variables and not the local environment variables. #Mofi explains it in detain on the comments of my post. I switched my batch file as follows:
START %CD%\Miniconda3-latest-Windows-x86_64.exe /InstallationType=JustMe /AddToPath=1 /RegisterPython=0 /S /D=%CD%\miniconda3
TIMEOUT 40
set PATH=%PATH%;%CD%\miniconda3\Library\mingw-w64\bin;%CD%\miniconda3\Library\usr\bin;%CD%\miniconda3\Library\bin;%CD%\miniconda3\Scripts
CALL conda activate .\envs_dir
python python_script.py
UPDATE
For a more robust batch script, following the comments of #Mofi, I changed my script to:
"%~dp0Miniconda3-latest-Windows-x86_64.exe" /InstallationType=JustMe /AddToPath=1 /RegisterPython=0 /S /D="%~dp0miniconda3"
set "PATH=%PATH%;%~dp0miniconda3\Library\mingw-w64\bin;%~dp0miniconda3\Library\usr\bin;%~dp0miniconda3\Library\bin;%~dp0miniconda3\Scripts"
call "%~dp0miniconda3\Library\bin\conda.bat" activate "%~dp0envs_dir"
"%~dp0envs_dir\python.exe" "%~dp0python_script.py"
When I open the anaconda prompt the window that opens, shows:
(base) C:\Users\sherv>
So I deactivate it and get:
C:\Users\sherv>
which is the same thing when I open cmd. From here there is there any way that I can reactivate conda? Because the command words like "conda -v" or "activate base", etc, don't work.
Also, the conda prompt is a shortcut so when I right-click and select "open file location", it goes to windows\system32\cmd. So I don't understand why I can't activate conda environments from cmd if it's the same thing?
This is the anaconda prompt shortcut:
When I open file location its the cmd:
I have even tried to add it to that path just in case it might work?
PS. I'm very new to all this and trying to connect some dots; sorry if it's a stupid question.
ok, so the path first opens the cmd (which is why the shortcut points at it, but then from there, from within the cmd, it runs C:\Users\sherv\Anaconda3\Scripts\activate.bat. Is there anyway I can have the batch file commands run from cmd without having to write out the path every time? I added the path for the batch file but it didn't work
The reason why the anaconda prompt shortcut leads to cmd is because it needs to open cmd first and then run a batch file which activates the conda environment. What I had done was to add the batch file to the path but I wasn't using the correct commands to run the conda environment. Therefore, all the keywords such as activate etc didn't work.
Simply type activate.bat and the file which is added to the path is opened which takes you to the base conda environment.
You can use this method to run different programs on different APIs and export the result back and analyse it.
Thanks for downvoting my question :)
I figured out how to do it, in my case with miniconda so it might be slightly different.
Find conda.exe in the Scripts folder. For me it was C:\Users\[SomeUser]\miniconda3\Scripts\conda.exe
Open command prompt and navigate to that same directory
Run conda init cmd.exe - To see more info on this command, you can run conda init --help, where it says "Initialize conda for shell interaction. [Experimental]"
Now after reloading command prompt, from anywhere you should be able to do conda activate WhateverEnvName and it will start it in that environment
If you want to make a batch file that opens to the environment, you can use cmd.exe /k conda activate WhateverEnvName
Alternatively, if you don't want to just open the environment, but actually want to launch a python script directly using that environment, you can type the full path to the python.exe in that environment folder, and then the relative path of the python script to run with that environment.
For example, say you open the command prompt in some arbitrary directory that contains "myscript.py" that you want to run with an environment called "whateverEnv".
You'd do: C:\Users\SomeUserName\miniconda3\envs\whateverEnv\python.exe myscript.py
You could also put that same line into a batch file.
I have a command that only runs correctly inside a Python virtual environment I've configured (as intended). I know that I can run the command as
$ cmd args
once I've activated the venv. But (due to the constraints of the tool I'm using) I need to activate run (and deactivate?) in one line: something equivalent to running
$ activate_somehow cmd args
outside the command line.
Is there a way to do this?
You can generally run something in a virtual environment simply by using a fully qualified path to the script. For example, if I have:
virtualenv .venv
Then I can install something into that virtual environment without activating it by running:
.venv/bin/pip install foo
This should be true for anything installed using standard Python mechanisms.
After looking into the generated bin/activate script, it seems like the only thing relevant to python is the VIRTUAL_ENV variable, so this should be enough to get going:
$ env VIRTUAL_ENV=path/to/venv python ...
Note that the python executable in the bin directory of target environment is just a symlink to globally installed interpreter, which does nothing other that setting process executable path. Assuming the program does not make use of it, utilizing the main binary itself seems harmless. In case you have installed a package which in turn installs some executables, just specify the absolute path:
$ env VIRTUAL_ENV=path/to/venv path/to/venv/bin/executable
You can create a simple wrapper script which runs activate, executes your command, and then deactivates simply by exiting the script in which your environment was activated.
#!/bin/sh
. ${venv-./env}/bin/activate
"$#"
This lets you set the environment variable venv to the path of the environment you want to use, or else uses ./env if it is unset. Perhaps a better design would be to pass the env as the first parameter:
#!/bin/sh
. "$1"/bin/activate
shift
"$#"
Either way, save this somewhere in your PATH ($HOME/bin is a common choice for your private scripts) and give it executable permission.
I found venv-run which should do what you ask:
pip install venv-run
venv-run cmd args
Larsk's answer is probably cleaner, but this is another possible way.
Assuming you use UNIX and your user is user and you have a virtual environment in home (any) directory, ie /home/user/venv, you can make a script like:
#!/bin/sh
export VIRTUAL_ENV=/home/user/venv
export PATH=/home/user/venv/bin:$PATH
python3 "$#"
We can make this script executable (eg call it venv-python3 and do chmod +x venv-python3) and call it as such, or put it some place discoverable in PATH - let's say alongside python. Assuming you have sudo rights:
sudo cp venv-python3 /usr/bin/venv-python3
Then we can call that instead of the python callable. Since the variables are set within the script, explicit call on deactivate is not necessary at exit.
Example:
user#machine ~ % venv-python3 --help
This works for at least for virtualenv version 20.0.17 but if adopted, you should be keeping an eye on what variables bin/activate sets, if this ever changes.
Yes, you can execute the python file using a virtual environment in a single line of command on windows.
venv\Scripts\activate&&python fall_detector.py
I installed pgadmin4 in my home directory in a virtual environment called "pgadmin4".
I use fish shell and it runs perfectly fine with:
~/pgadmin4/bin/python3 ~/pgadmin4/lib/python3.10/site-packages/pgadmin4/pgAdmin4.py
Just in case this helps somebody.
I'd like to use Windows Task Scheduler to run a python script within a virtual environment. I'd like the Scheduler to run a .bat file that will
activate the virtualenv
run the script
These steps work together from the command line, and they work individually in a .bat, but I can't seem to get them to work together from the .bat. It seems the virtualenv is not fully activated when I try to execute the python script and confused as to why.
My .bat looks like this:
call workon venv
cd path/to/Python/proj
python -m script.py
I've tried adding timeouts immediately after the call to workon and tried moving the workon to seperate .bat called from my first file, but the other lines still execute before the virtualenv is activated. Any help is greatly appreciated!
You do not need to activate the virtual environment while running in .bat. All you need to do is to run the python.exe file in your virtual environment.
{path to virtual environment directory}/Scripts/python.exe path/to/your/file.py
In Windows Task Scheduler you can specify the path in which the command prompt will open. So all you need to do is when adding the action, use path to your python in the field Program/script, the name of the file to be run in Add arguments field, and the path to your file.py in Start in field.
P.S if you are reading or writing files in your python file, note that your path will be relative to the one you specify in your start in field in the Action window
You can use an ampersand & operator in a oneliner batch file.
call workon venv & cd path/to/Python/proj & python -m script.py
It will run each command after the other.
You can also double up the ampersand to make it a conditional operator. &&:
call workon venv && cd path/to/Python/proj && python -m script.py
Here the command will only run, if the previous command completed successfully, in other words ERRORLEVEL = 0
Just type
call .\venv\Scripts\activate.bat
in the .bat file and any command afterwards will see the venv activated
for the record call in a cmd pauses the execution of the current script, executes the called one and then resumes.
Create .bat file
write virtual environment activate script location and python file location as below use '&' operator to run two commands.
as below:
"E:\Call Allocation Engine\Development\development_env\Scripts\"activate & python run.py
https://i.stack.imgur.com/31Gkh.png
finally place this file in desired folder and run using cmd.
E:\Call Allocation Engine\Development\Optimisation\Scheduling>file_name.bat
this script will activate virtual environment and run your python code in that environment.
Another way to do this is to make a shortcut of the batch file and then change the "Start in" field.
After that remember to use the full paths in your batch file since it will be running from a difference location.
Edit activate.bat and place this line at the bottom:
python yourscript.py
Schedule the activate.bat itself and it will automatically run your script after the virtual environment activated.
I am setting up calls to python (Anaconda distribution) via BAT files and the windows task scheduler.
I've now used environments for the first time and was trying to set a .bat file up as below:
activate [my_env]
python my_script.py
deactivate
Unfortunately it appears that the second command does not get executed.
Use the 'call' command when activating/deactivating the environment.
call activate [my_env]
python my_script.py
call conda deactivate
See https://github.com/conda/conda/issues/794
Are you sure you need a batch file? I think this should work.
cmd "/c activate [my_env] && python my_script.py && deactivate"
When I made a simple file containing
print("Hello")
Which I called myprint.py and ran
cmd "/c activate anaconda33 && python myprint.py && deactivate"
This worked for me. You could also put this in a one line batch file.
All activate does is put the environment in the front of the PATH. You can just call the absolute path to the python in the environment you want, like C:\Anaconda\python my-script.py.