如何在 Bash 脚本中激活 virtualenv [英] How to source virtualenv activate in a Bash script

查看:30
本文介绍了如何在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆