Sunday, September 3, 2017

[Python] Use Virtualenv, venv to isolate environments

 Python   Virtualenv    venv  




▌Introduction


We will learn how to use Virtualenv and venv(available in Python 3) for running isolated environments with different versions of packages.



▌Environment

▋Windows 10
▋Git bash
▋Python 3.6.2



▌Virtualenv


▋Install Virtualenv

$ python –m pip install virtualenv


▋Create virtual environment

$  winpty virtualenv {environment_name} [--no-site-packages] [--python=/c/Python25/python.exe]


[--no-site-packages]
Do not access to global site-packages. (Default)


[--system-site-packages]
The virtual environment will inherit packages from site-packages.


[--python=/c/Python25/python.exe]
Specify the Python interpreter to use in this virtual environment.


For example,
winpty virtualenv myProject --no-site-packages --python=/C/Users/JB/AppData/Local/Programs/Python/Python36-32/python.exe

▋Activate and deactivate

To activate the virtual environment in Windows,

$ source {environment_name}/Scripts/activate

Which will result in appending the environment name as the prefix of shell command.



To deactivate it,

$ deactivate


Furthermore, we can force pip to be used only in an active virtual environment by adding the following line to your ~/.bashrc file.

$ export PIP_REQUIRE_VIRTUALENV=true

 



▌venv


venv is a package shipped with Python 3, no need to install it manually.

▋Create virtual environment

$ python -m venv {environment_name} [--system-site-packages]

For example,
python -m venv venv/MyProject


▋Activate and deactivate

▋Activate

$ source {environment_name}/Scripts/activate


▋Deactivate

$ deactivate



▌Reference







No comments:

Post a Comment