virtualenv

最後更新: 2019-08-20

介紹

virtualenv - a tool to create isolated Python environments.

 


Usage

 

# Install

# epel

yum install python-virtualenv

# The basic usage

# 建立名叫 ENV 的 virtualenv

virtualenv ENV                     # Size >= 12M

它會建立一個 Folder 叫 "ENV", 內有

 - ENV/lib/pythonX.X/site-packages

 - ENV/bin/python

# activate that virtual environment

source ENV/bin/activate

# 行完 script 後, shell prompt 會變成

(VIRTUAL_ENV_DISABLE_PROMPT)  <-- 在這個例子, 它是 ENV

# 安裝要的 package (pip)

i.e.

pip install --upgrade pip

pip install sqlalchemy

pip install MySQL-python

# 離開 virtual environment

deactivate       # to undo the changes to your $PATH.

i.e.

(venv-vncdotool) server:script# deactivate

# Script 內應用

以後只要某 script 想用另一個 ENV, 那只要加以下一句在檔頭即可

#!/path/to/ENV/bin/python

.........................

 


Setup a Python Virtual Environment [進階]

 

# Create a new virtual environment

virtualenv --no-site-packages --distribute px

OR

# use a Python interpreter(/usr/bin/python26) of your choice

virtualenv -p /usr/bin/python26 venv

* --distribute option to use the setuptools fork Distribute.

* --no-site-packages flag is deprecated; it is now the default behavior. (debian7)

   (not include the packages that are installed globally)

 


應用

 

應用1: keep your environment consistent

# “freeze” the current state of the environment packages

pip freeze > requirements.txt

# list of all the packages in the current environment

cat requirements.txt

#  re-create the environment

virtualenv ENV

source venv-vncdo/bin/activate

pip install -r requirements.txt

 


Troubleshoot

 

[問題1] 行 "virtualenv -p python3 py3" 時遇到 error

解決

pip install --upgrade virtualenv

 


move python virtualenv to another folder (or renaming)

 

By default virtualenv does not support the renaming of environments.

It is safer to just delete the virtualenv directory and create a new one

# 可能方案

[A]

pip install virtualenvwrapper

cpvirtualenv <wrong_name> <correct_name>

rmvirtualenv <wrong_name>

[B]

1. change the $VIRTUAL_ENV environment variable in the myvenv/bin/activate script

2. --relocatable     # Make an EXISTING virtualenv environment relocatable. (relative path)

virtualenv --relocatable venv-vncdo

如果有以下 Error, 那就要重安

Script /mydata/script/reset_win7/venv-vncdo/bin/vncdo cannot be made relative
 (it's not a normal script that starts with #!/mydata/script/reset_win7/venv-vncdo/bin/python)

Absolute path is still hardcoded in the activate script @@||

 

 


Doc

 

http://www.virtualenv.org/en/latest/virtualenv.html#usage

 


 

 

 

Creative Commons license icon Creative Commons license icon