Menu
What is Virtualenv?
Running virtualenv with the option -no-site-packages will not include the packages that are installed globally. This can be useful for keeping the package list clean in case it needs to be accessed later. This is the default behavior for virtualenv 1.7 and later.
A Virtual Environment, put simply, is an isolated working copy of Python which
allows you to work on a specific project without worry of affecting other projects
allows you to work on a specific project without worry of affecting other projects
- Linux/Mac Users can use the following command to install 'pipenv' after installing LinuxBrew. Brew install pipenv. Creating a virtualenv for the project. For creating the 'virtualenv' for the project, use the following command. Pipenv shell The command 'pipenv' creates a new 'virtualenv.
- Installing packages using pip and virtual environments¶. This guide discusses how to install packages using pip and a virtual environment manager: either venv for Python 3 or virtualenv for Python 2. These are the lowest-level tools for managing Python packages and are recommended if higher-level tools do not suit your needs.
It enables multiple side-by-side installations of Python, one for each project.
It doesn’t actually install separate copies of Python, but it does provide a
clever way to keep different project environments isolated.
clever way to keep different project environments isolated.
Verify if Virtualenv is installed
There is a chance that virtualenv is already installed on your system.
Run the following command in your terminal
If you see a version number (in my case 1.6.1), it’s already installed.
>>1.6.1
>>1.6.1
Install Virtualenv
There are a number of ways to install virtualenv on your system.
Setup and Use Virtualenv
Once you have virtualenv installed, just fire up a shell and create your own
environment.
environment.
First create a directory for your new shiny isolated environment
To create a folder for your new app that includes a clean copy of Python,
simply run:
simply run:
(add –no-site-packages if you want to isolate your environment from the main site
packages directory)
packages directory)
To begin working with your project, you have to cd into your directory (project)
and activate the virtual environment.
and activate the virtual environment.
![Python Python](/uploads/1/1/8/9/118990300/668070087.png)
Lastly, activate your environment:
Notice how the prompt of your shell changed to show the active environment.
That is how you can see that you’re in your new environment.
Recommended Python Training
For Python training, our top recommendation is DataCamp.
Any packages you install now using pip or easy_install get installed into
my_new_app/lib/python2.7/site-packages.
my_new_app/lib/python2.7/site-packages.
To exit your virtualenv just type “deactivate”.
What did Virtualenv do?
Packages installed here will not affect the global Python installation.
Virtualenv does not create every file needed to get a whole new python environment
It uses links to global environment files instead in order to save disk space end
speed up your virtualenv.
speed up your virtualenv.
Therefore, there must already have an active python environment installed on your
system.
system.
Install a package in your Virtualenv
If you look at the bin directory in your virtualenv, you’ll see easy_install which
has been modified to put eggs and packages in the virtualenv’s site-packages
directory.
has been modified to put eggs and packages in the virtualenv’s site-packages
directory.
To install an app in your Virtualenv:
You don’t have to use sudo since the files will all be installed in the virtualenv
/lib/python2.7/site-packages directory which was created as your own user account
/lib/python2.7/site-packages directory which was created as your own user account
That’s it, I hope that you learned something from this post
For further reading, please see:
http://flask.pocoo.org/docs/installation/#virtualenv
http://pypi.python.org/pypi/virtualenv
Getting-started-with-virtualenv-isolated-python-environments/
http://flask.pocoo.org/docs/installation/#virtualenv
http://pypi.python.org/pypi/virtualenv
Getting-started-with-virtualenv-isolated-python-environments/
Recommended Python Training
For Python training, our top recommendation is DataCamp.
Source code:Lib/venv/
The
venv
module provides support for creating lightweight “virtualenvironments” with their own site directories, optionally isolated from systemsite directories. Each virtual environment has its own Python binary (whichmatches the version of the binary that was used to create this environment) andcan have its own independent set of installed Python packages in its sitedirectories.See PEP 405 for more information about Python virtual environments.
See also
Creating virtual environments¶
Creation of virtual environments is done by executing thecommand
venv
:Running this command creates the target directory (creating any parentdirectories that don’t exist already) and places a
pyvenv.cfg
file in itwith a home
key pointing to the Python installation from which the commandwas run (a common name for the target directory is .venv
). It also createsa bin
(or Scripts
on Windows) subdirectory containing a copy/symlinkof the Python binary/binaries (as appropriate for the platform or argumentsused at environment creation time). It also creates an (initially empty)lib/pythonX.Y/site-packages
subdirectory (on Windows, this isLibsite-packages
). If an existing directory is specified, it will bere-used.Deprecated since version 3.6:
pyvenv
was the recommended tool for creating virtual environments forPython 3.3 and 3.4, and is deprecated in Python 3.6.Changed in version 3.5: The use of
venv
is now recommended for creating virtual environments.On Windows, invoke the
venv
command as follows:Alternatively, if you configured the
PATH
and PATHEXT
variables foryour Python installation:The command, if run with
-h
, will show the available options:Changed in version 3.8: Add
--upgrade-deps
option to upgrade pip + setuptools to the latest on PyPIChanged in version 3.4: Installs pip by default, added the
--without-pip
and --copies
optionsChanged in version 3.4: In earlier versions, if the target directory already existed, an error wasraised, unless the
--clear
or --upgrade
option was provided.Note
While symlinks are supported on Windows, they are not recommended. Ofparticular note is that double-clicking
python.exe
in File Explorerwill resolve the symlink eagerly and ignore the virtual environment.Note
On Microsoft Windows, it may be required to enable the
Activate.ps1
script by setting the execution policy for the user. You can do this byissuing the following PowerShell command:PS C:> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
See About Execution Policiesfor more information.
The created
pyvenv.cfg
file also includes theinclude-system-site-packages
key, set to true
if venv
isrun with the --system-site-packages
option, false
otherwise.Activate Virtualenv Windows
Unless the
--without-pip
option is given, ensurepip
will beinvoked to bootstrap pip
into the virtual environment.Multiple paths can be given to
venv
, in which case an identical virtualenvironment will be created, according to the given options, at each providedpath.Once a virtual environment has been created, it can be “activated” using ascript in the virtual environment’s binary directory. The invocation of thescript is platform-specific (<venv> must be replaced by the path of thedirectory containing the virtual environment):
Platform | Shell | Command to activate virtual environment |
---|---|---|
POSIX | bash/zsh | $ source <venv>/bin/activate |
fish | $ source <venv>/bin/activate.fish | |
csh/tcsh | $ source <venv>/bin/activate.csh | |
PowerShell Core | $ <venv>/bin/Activate.ps1 | |
Windows | cmd.exe | C:> <venv>Scriptsactivate.bat |
PowerShell | PS C:> <venv>ScriptsActivate.ps1 |
You don’t specifically need to activate an environment; activation justprepends the virtual environment’s binary directory to your path, so that“python” invokes the virtual environment’s Python interpreter and you can runinstalled scripts without having to use their full path. However, all scriptsinstalled in a virtual environment should be runnable without activating it,and run with the virtual environment’s Python automatically.
You can deactivate a virtual environment by typing “deactivate” in your shell.The exact mechanism is platform-specific and is an internal implementationdetail (typically a script or shell function will be used).
New in version 3.4:
fish
and csh
activation scripts.New in version 3.8: PowerShell activation scripts installed under POSIX for PowerShell Coresupport.
Note
A virtual environment is a Python environment such that the Pythoninterpreter, libraries and scripts installed into it are isolated from thoseinstalled in other virtual environments, and (by default) any librariesinstalled in a “system” Python, i.e., one which is installed as part of youroperating system.
A virtual environment is a directory tree which contains Python executablefiles and other files which indicate that it is a virtual environment.
Common installation tools such as setuptools and pip work asexpected with virtual environments. In other words, when a virtualenvironment is active, they install Python packages into the virtualenvironment without needing to be told to do so explicitly.
When a virtual environment is active (i.e., the virtual environment’s Pythoninterpreter is running), the attributes
sys.prefix
andsys.exec_prefix
point to the base directory of the virtualenvironment, whereas sys.base_prefix
andsys.base_exec_prefix
point to the non-virtual environment Pythoninstallation which was used to create the virtual environment. If a virtualenvironment is not active, then sys.prefix
is the same assys.base_prefix
and sys.exec_prefix
is the same assys.base_exec_prefix
(they all point to a non-virtual environmentPython installation).When a virtual environment is active, any options that change theinstallation path will be ignored from all
distutils
configurationfiles to prevent projects being inadvertently installed outside of thevirtual environment.When working in a command shell, users can make a virtual environment activeby running an
activate
script in the virtual environment’s executablesdirectory (the precise filename and command to use the file isshell-dependent), which prepends the virtual environment’s directory forexecutables to the PATH
environment variable for the running shell. Thereshould be no need in other circumstances to activate a virtualenvironment; scripts installed into virtual environments have a “shebang”line which points to the virtual environment’s Python interpreter. This meansthat the script will run with that interpreter regardless of the value ofPATH
. On Windows, “shebang” line processing is supported if you have thePython Launcher for Windows installed (this was added to Python in 3.3 - seePEP 397 for more details). Thus, double-clicking an installed script in aWindows Explorer window should run the script with the correct interpreterwithout there needing to be any reference to its virtual environment inPATH
.API¶
The high-level method described above makes use of a simple API which providesmechanisms for third-party virtual environment creators to customize environmentcreation according to their needs, the
EnvBuilder
class.venv.
EnvBuilder
(system_site_packages=False, clear=False, symlinks=False, upgrade=False, with_pip=False, prompt=None, upgrade_deps=False)¶The
EnvBuilder
class accepts the following keyword arguments oninstantiation:system_site_packages
– a Boolean value indicating that the system Pythonsite-packages should be available to the environment (defaults toFalse
).clear
– a Boolean value which, if true, will delete the contents ofany existing target directory, before creating the environment.symlinks
– a Boolean value indicating whether to attempt to symlink thePython binary rather than copying.upgrade
– a Boolean value which, if true, will upgrade an existingenvironment with the running Python - for use when that Python has beenupgraded in-place (defaults toFalse
).with_pip
– a Boolean value which, if true, ensures pip isinstalled in the virtual environment. This usesensurepip
withthe--default-pip
option.prompt
– a String to be used after virtual environment is activated(defaults toNone
which means directory name of the environment wouldbe used). If the special string'.'
is provided, the basename of thecurrent directory is used as the prompt.upgrade_deps
– Update the base venv modules to the latest on PyPI
Changed in version 3.4: Added the
with_pip
parameterNew in version 3.9: Added the
upgrade_deps
parameterCreators of third-party virtual environment tools will be free to use theprovided
EnvBuilder
class as a base class.The returned env-builder is an object which has a method,
create
:create
(env_dir)¶Create a virtual environment by specifying the target directory(absolute or relative to the current directory) which is to contain thevirtual environment. The
create
method will either create theenvironment in the specified directory, or raise an appropriateexception.The
create
method of the EnvBuilder
class illustrates thehooks available for subclass customization:Each of the methods
ensure_directories()
,create_configuration()
, setup_python()
,setup_scripts()
and post_setup()
can be overridden.ensure_directories
(env_dir)¶Creates the environment directory and all necessary directories, andreturns a context object. This is just a holder for attributes (such aspaths), for use by the other methods. The directories are allowed toexist already, as long as either
clear
or upgrade
werespecified to allow operating on an existing environment directory.create_configuration
(context)¶Creates the
pyvenv.cfg
configuration file in the environment.setup_python
(context)¶Creates a copy or symlink to the Python executable in the environment.On POSIX systems, if a specific executable
python3.x
was used,symlinks to python
and python3
will be created pointing to thatexecutable, unless files with those names already exist.setup_scripts
(context)¶Installs activation scripts appropriate to the platform into the virtualenvironment.
upgrade_dependencies
(context)¶Upgrades the core venv dependency packages (currently
pip
andsetuptools
) in the environment. This is done by shelling out to thepip
executable in the environment.New in version 3.9.
post_setup
(context)¶A placeholder method which can be overridden in third partyimplementations to pre-install packages in the virtual environment orperform other post-creation steps.
Changed in version 3.7.2: Windows now uses redirector scripts for
python[w].exe
instead ofcopying the actual binaries. In 3.7.2 only setup_python()
doesnothing unless running from a build in the source tree.Changed in version 3.7.3: Windows copies the redirector scripts as part of
setup_python()
instead of setup_scripts()
. This was not the case in 3.7.2.When using symlinks, the original executables will be linked.In addition,
EnvBuilder
provides this utility method that can becalled from setup_scripts()
or post_setup()
in subclasses toassist in installing custom scripts into the virtual environment.install_scripts
(context, path)¶path is the path to a directory that should contain subdirectories“common”, “posix”, “nt”, each containing scripts destined for the bindirectory in the environment. The contents of “common” and thedirectory corresponding to
os.name
are copied after some textreplacement of placeholders:__VENV_DIR__
is replaced with the absolute path of the environmentdirectory.__VENV_NAME__
is replaced with the environment name (final pathsegment of environment directory).__VENV_PROMPT__
is replaced with the prompt (the environmentname surrounded by parentheses and with a following space)__VENV_BIN_NAME__
is replaced with the name of the bin directory(eitherbin
orScripts
).__VENV_PYTHON__
is replaced with the absolute path of theenvironment’s executable.
The directories are allowed to exist (for when an existing environmentis being upgraded).
There is also a module-level convenience function:
venv.
create
(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None)¶Create an
EnvBuilder
with the given keyword arguments, and call itscreate()
method with the env_dir argument.Virtualenv Mac Python 3
Changed in version 3.4: Added the
with_pip
parameterChanged in version 3.6: Added the
prompt
parameterAn example of extending EnvBuilder
¶
The following script shows how to extend
EnvBuilder
by implementing asubclass which installs setuptools and pip into a created virtual environment:This script is also available for download online.