在OS X上以32位模式运行非系统Python和virtualenv
简短问题
使用virtualenv或virtualenvwrapper,能否在调用python
时加上一个前缀,以链接到特定的虚拟环境?
背景
我想使用一个通过brew安装的 Python 2.7来创建多个虚拟环境,但有些需要在64位模式下运行,其他的则在32位模式下运行。
下面是我在OS X开发环境中的典型设置。我想在调用python
时加上arch -i386
这个前缀,以强制python以32位模式运行。最重要的是,这个前缀应该在调用workon env32
之后才添加(如示例所示)。我知道我可以在我的.bash_profile中设置一个别名,但每次创建或删除虚拟环境时都需要修改这个别名。
编辑
为了更详细地说明我在使用简单别名时遇到的问题,可能会有多个32位的虚拟环境。也就是说,理想情况下,调用workon
时应该自动将前缀添加到python
的调用中,这样在终端中的工作流程就保持一致。也就是说,在调用workon env_x_32
后,我只需要使用python
,而arch -i386
的部分对我来说是透明的。
Python安装:
> brew install python --framework --universal
创建虚拟环境(在安装pip、virtualenv和virtualenvwrapper后):
> mkvirtualenv env_1_64 --no-site-packages
> mkvirtualenv env_1_32 --no-site-packages
> mkvirtualenv env_2_64 --no-site-packages
> mkvirtualenv env_2_32 --no-site-packages
64位使用:
> workon env_1_64
> python myscript.py
> workon env_2_64
> python my_other_project_script.py
32位使用:(当前/非理想)
> workon env_1_32
> arch -i386 python myscript.py
> workon env_2_32
> arch -i386 python my_other_project_script.py
32位使用:(理想)
> workon env_1_32
> python my_32bit_project.py # Note that the arch -i386 would be transparent
解决方案
根据Sean的评论进行操作:
我在我想以32位运行的环境的激活/停用脚本中添加了一个别名。详细信息见下文。
env_1_32: 激活脚本
# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly
deactivate () {
alias python='python' # <---- Added this line
# reset old environment variables
if [ -n "$_OLD_VIRTUAL_PATH" ] ; then
PATH="$_OLD_VIRTUAL_PATH"
export PATH
unset _OLD_VIRTUAL_PATH
fi
# ****** Removed Content to keep the post shorter*********
}
# unset irrelavent variables
deactivate nondestructive
VIRTUAL_ENV="/Users/Adam/.envs/env_1_32"
export VIRTUAL_ENV
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "$BASH" -o -n "$ZSH_VERSION" ] ; then
hash -r
fi
# ****** Removed Content to keep the post shorter*********
alias python='arch -i386 python' # <---- Added this line to run as 32bit
1 个回答
6
给你的激活脚本添加一个别名,这样每次想用虚拟环境的时候就可以激活它。
$ cd env32
$ echo "alias python='arch -i386 python'" >> bin/activate
$ source bin/activate
$ python myscript.py