启动终端时激活默认的virtualenv(使用bashrc)

use*_*719 9 python bash virtualenv

我系统中的默认python版本是2.6.6.我安装了virtualenv,每当我打开终端时,我都希望默认的virtualenv为2.7.

所以,我在〜/ .bashrc文件中添加了以下命令:

source $HOME/virtualenvs/py2.7/bin/activate
Run Code Online (Sandbox Code Playgroud)

现在每当我通过点击Gnome环境中的图标启动一个终端(即,我已经登录到机器并在Gnome中打开一个新的终端窗口(xterm)),shell符号如下所示:

    (py2.7)(py2.7)
Run Code Online (Sandbox Code Playgroud)

看起来好像我在另一个virtualenv里面有一个virtualenv.更糟糕的是,我只能停用一个virtualenv而不是另一个,如下所示:

    (py2.7)(py2.7)deactivate 
    (py2.7)python
    Python 2.7.5 (default, Jun 28 2013, 14:53:08) 
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> exit()
    (py2.7)deactivate
    bash: deactivate: command not found
    (py2.7)python
    Python 2.7.5 (default, Jun 28 2013, 14:53:08) 
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,虽然我系统中的默认python是2.6,但我仍然坚持使用virtualenv(2.7)

如果我通过Ctrl + Alt + F2切换到文本虚拟控制台并登录,看起来很正常.

    (py2.7)[username@host ~]$
Run Code Online (Sandbox Code Playgroud)

我可以停用并返回系统的默认python 2.6.

    (py2.7)[username@host ~]$ python
    Python 2.7.5 (default, Jun 28 2013, 14:53:08) 
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> exit()
    (py2.7)[username@host ~]$ deactivate
    [username@host ~]$ python
    Python 2.6.6 (r266:84292, Oct 12 2012, 14:23:48) 
    [GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 
Run Code Online (Sandbox Code Playgroud)

有什么问题?每当我在Gnome中打开终端时,是否可以将默认的virtualenv设置为2.7?

我的Linux发行版是RedHat 6.

Wol*_*lph 5

这个怎么样?测试你是否已经在virtualenv :)

test -z "$VIRTUAL_ENV" && source $HOME/virtualenvs/py2.7/bin/activate
Run Code Online (Sandbox Code Playgroud)


God*_*ebh 5

沃尔夫的回答对我不起作用。相反,我在 .bashrc 中使用了以下测试:

if (tty -s); then
    source /pathto/virtualenvs/py2.7/bin/activate
fi
Run Code Online (Sandbox Code Playgroud)

如果标准输入是终端,则 tty 以 0 退出,否则以 1 退出。如果您不对此进行测试,它会以某种方式执行两次:一次是在登录时执行,另外一次是在您打开终端时执行。

编辑:如果你现在执行“屏幕”,你将再次得到 (py2.7)(py2.7)user@computer ]$