Creating a Python virtual environment
Published May 14, 2024, 5:58 a.m. by cloudblog
When you write Python applications, you will usually use packages and modules that are not included in the standard Python library. You may have Python applications that require a different version of the same module. However, only a specific version of a module can be installed system-wide. If you upgrade a module version for an application, you might end up breaking other applications that require an older version of that module.
To address this issue, you can use Python virtual environments. With virtual environments, you can install Python modules in an isolated location rather than installing them globally. Each virtual environment has its own Python binary and can have its own independent set of installed Python packages in its site directories.
Since version 3.3, Python comes with the venv
library, which provides support for creating lightweight virtual environments. By using the Python venv
module to create isolated Python environments, you can use different package versions for different projects. Another advantage of using venv
is that you won’t need any administration privileges to install Python packages.
If you are using Linux or macOS, create an isolated environment with the following command:
python -m venv my_env
Remember to use python3
instead of python
if your system comes with Python 2 and you installed Python 3.
If you are using Windows, use the following command instead:
py -m venv my_env
This will use the Python launcher in Windows.
The previous command will create a Python environment in a new directory named my_env/
. Any Python libraries you install while your virtual environment is active will go into the my_env/lib/python3.10/site-packages
directory.
If you are using Linux or macOS, run the following command to activate your virtual environment:
source my_env/bin/activate
If you are using Windows, use the following command instead:
.\my_env\Scripts\activate
The shell prompt will include the name of the active virtual environment enclosed in parentheses like this:
(my_env) zenx@pc:~ zenx$
You can deactivate your environment at any time with the deactivate
command. You can find more information about venv
at https://docs.python.org/3/library/venv.html.
(cloudblog) [cloudblog@cloudblog ~]$ cat .bash_profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:/usr/local/git/bin:$HOME/.local/bin:$HOME/bin
export WORKON_HOME=/home/cloudblog/bin/virtualenvs
source /home/cloudblog/bin/activate
export LD_LIBRARY_PATH=/usr/local/lib
export PATH
Similar posts
0 comments
There are no comments.