简体   繁体   English

在批处理文件中激活 Python 虚拟环境

[英]Activating Python Virtual env in Batch file

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.我正在尝试制作一个批处理脚本(称为run_windows )来检查 python 虚拟环境是否存在,如果不存在,则创建它然后激活它,安装要求并最后运行一些 python 代码。

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:但是,当我运行脚本时,代码在第 4 行退出: %VIRTUAL_ENV%\Scripts\activate没有错误:

在此处输入图像描述

Few things:一些事情:

  • Running the .bat or bash version of activate in is not predictable, Activate.ps1 is found in newer releases.中运行.batbash版本的激活是不可预测的, Activate.ps1可以在较新的版本中找到。 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. windows(Windows 中的 .bat 或 .cmd)中的脚本自上而下处理, :<ANCHOR>不会像 Sub 或 Function 那样被跳过。

I have only worked with the Conda version of activate.ps1 and it adds some nice commands.我只使用了激活.ps1 的 Conda 版本,它添加了一些不错的命令。 Had a quick look in standard Python 3.10.5 and it does not add commands but should work fine.快速浏览了标准 Python 3.10.5,它没有添加命令,但应该可以正常工作。

Edit: Added that while working, is not the best option to use the bash version of activate编辑:补充说,在工作时,不是使用激活的 bash 版本的最佳选择

Here is a quick example of your batch file rearranged, and using the Call command as previously instructed.这是一个重新排列批处理文件的快速示例,并按照前面的说明使用Call命令。

@Echo Off

Set "VIRTUAL_ENV=mat_visualizer_env"

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

If Not Exist "%VIRTUAL_ENV%\Scripts\activate.bat" Exit /B 1

Call "%VIRTUAL_ENV%\Scripts\activate.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.此外,您还没有明确%1应该是什么,或者它来自哪里,所以我不能保证这是否正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM