“源”的批次等价物在 Windows 上:如何从 virtualenv 运行 Python 脚本
我已经编写了相当多的 bash 脚本,但在 Windows 上编写的批处理脚本却很少。我正在尝试激活 Python virtualenv,运行 Python 脚本,然后在脚本退出时停用 virtualenv。
我有一个名为 env
的文件夹,它是我的 virtualenv,还有一个名为 work 的文件夹,其中包含我的脚本。
这是我到目前为止所得到的:
%~dp0env\Scripts\activate.bat
python %~dp0work\script.py
deactivate
但是,当我运行脚本时,它会激活 virtualenv 然后停止。它不会到达第二行并运行 Python 脚本。有没有办法“获取”激活脚本文件夹,以便可以像我从命令行调用 activate.bat
一样运行批处理脚本的其余部分?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想说,您只需要在 activate.bat 调用前面添加“call”,以确保执行 activate 后恢复当前的批处理文件:
考虑对
deactivate.bat
执行相同的操作。此外,如果您想确保当前的 cmd.exe 环境不会因调用批处理文件而受到污染,请考虑将命令包装在setlocal
/endlocal
命令对中。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:
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 asetlocal
/endlocal
command pair.我制作了一个指向 cmd /k "path/to the/script/activate.bat" 的 .lnk 文件,它可以工作。
CMD 参数&选项
I made a .lnk file that points to
cmd /k "path/to the/script/activate.bat"
, and it works.CMD parameters & options
我想您只想在 Windows 中执行与 Linux Bash/shell 中预期相同的命令。当我想启动 virtualenv 时,我实际上位于其顶级目录中,Linux 命令将是“source bin/activate”。
在Windows上模拟这个行为是没有问题的。就我个人而言,我将一个名为
activate.bat
的批处理文件放在 PATH 环境变量中的某个位置,如下所示: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: