如何在 Bash 脚本中激活 virtualenv

编程入门 行业动态 更新时间:2024-10-27 20:33:32
本文介绍了如何在 Bash 脚本中激活 virtualenv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何创建 Bash 脚本来激活 Python virtualenv?

How do you create a Bash script to activate a Python virtualenv?

我的目录结构如下:

.env bin activate ...other virtualenv files... src shell.sh ...my code...

我可以通过以下方式激活我的 virtualenv:

I can activate my virtualenv by:

user@localhost:src$ . ../.env/bin/activate (.env)user@localhost:src$

但是,从 Bash 脚本执行相同的操作没有任何作用:

However, doing the same from a Bash script does nothing:

user@localhost:src$ cat shell.sh #!/bin/bash . ../.env/bin/activate user@localhost:src$ ./shell.sh user@localhost:src$

我做错了什么?

推荐答案

当您获取源代码时,您将激活脚本加载到您的活动 shell 中.

When you source, you're loading the activate script into your active shell.

当您在脚本中执行此操作时,会将其加载到该 shell 中,该 shell 在您的脚本完成时退出,并且您将返回到原始的未激活的 shell.

When you do it in a script, you load it into that shell which exits when your script finishes and you're back to your original, unactivated shell.

最好的选择是在函数中进行

Your best option would be to do it in a function

activate () { . ../.env/bin/activate }

或别名

alias activate=". ../.env/bin/activate"

希望这会有所帮助.

更多推荐

如何在 Bash 脚本中激活 virtualenv

本文发布于:2023-10-09 10:23:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1475477.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   如何在   Bash   virtualenv

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!