如何通过shell脚本激活python虚拟环境 [英] How to activate python virtual environment by shell script

查看:90
本文介绍了如何通过shell脚本激活python虚拟环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个shell脚本.

I wrote a shell script as.

    source ve/bin/activate

当我使用命令运行脚本时,将其保存为 activate_shell.sh.

Saved it as activate_shell.sh latter when I ran the script with command.

    bash activate_shell.sh

脚本正在运行,没有错误,但虚拟环境没有被激活.

The script is being run with no error but the virtual environment is not being activated.

推荐答案

您的激活脚本路径 ve/bin/activate 是相对的.该脚本只能在一个目录中工作.但问题不在这里.

Your activation script path, ve/bin/activate, is relative. The script will only work from one directory. But the problem is not here.

bin/activate 有什么作用?它修改运行它的shell.这就是为什么您必须source 它而不是作为常规程序调用.

What does bin/activate do? It modifies the shell in which it runs. This is why you have to source it and not invoke as a regular program.

你写的脚本启动自己的shell副本(bash),激活里面的虚拟环境,然后退出,破坏刚刚激活的环境.如果您的脚本在获取 bin/activate 后调用 Python,它将是来自虚拟环境的 Python,而不是系统环境.

The script you wrote starts its own copy of shell (bash), activates the virtual environment inside it, and exits, destroying the just-activated environment. If your script invoked Python after sourcing the bin/activate, it would be the Python from the virtual environment, not the system one.

如果你想要一个简单的、易于输入的命令来激活一个 virtualenv,定义一个 shell 函数:

If you want a simple, easy-to-type command to activate a virtualenv, define a shell function:

ve() { source $1/bin/activate; }

(是的,在您的 shell 提示符中正确输入以上行.)

(Yes, type the above line right into your shell prompt.)

然后输入 ve foo 并且名为 foo 的 virtualenv 将在您当前的 shell 中被激活,前提是您位于正确的目录中.

Then type ve foo and virtualenv named foo will be activated in your current shell, provided that you're in the right directory.

如果您需要处理大量的 virtualenv,请查看 virtualenvwrapper.

Should you need to cope with a massive amount of virtualenvs, take a look at virtualenvwrapper.

这篇关于如何通过shell脚本激活python虚拟环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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