RSS Amplifier

rspk.org/weblog/rss.xml · Aug 7, 2019

Managing Python virtual environments with venv module

0
Sign in to vote or save

This site took too long to answer. You can still read it on the original site — the toolbar below keeps your place in the directory.

Managing Python virtual environments with venv module

Python is notorious for having a lot of different dependency management tools: virtualenv, virtualenvwrapper, pipenv, pyvenv, pipx, poetry, etc. But the `venv` module is a fairly new and easier to use tool that comes built-in with Python3.3+. To use it, just navigate to your project folder and do: ```shell $ python3 -m venv ./venv ``` Here, the second 'venv' is the name of the virtual environment we want to create. Now, the project structure looks like: ```shell $ tree myproject -L 2 myproject ├── myproject │   └── ... └── venv ├── bin ├── include ├── lib └── pyvenv.cfg ``` To activate the virtual environment, just do: ```shell $ source ./venv/bin/activate ``` Activating a virtualenv modifies your shell prompt showing the name of the virtualenv. This means that the Python interpreter and libraries installed into it are isolated from those installed in other virtual environments, and in the system Python, leaving the global environment unaffected: ```shell (venv) $ python3 -m pip install django (venv) $ python3 -m pip list Django (2.2.6) pip (9.0.1) pytz (2019.3) setuptools (39.0.1) sqlparse (0.3.0) ... (venv) $ ``` Before activating a virtual environment, the `python` command maps to the system version of python interpreter: ```shell $ which python3 /usr/bin/python3 ``` But with an active virtual environment, the `python` command maps to the interpreter binary inside the active virtualenv: ```shell $ (venv) which python3 /home/$USERNAME/myproject/venv/bin/python3 ``` To deactivate the virtual environment: ```shell (venv) $ deactivate ``` To export your dependencies to an external file: ```shell (venv) $ python3 -m pip freeze > requirements.txt ``` Deleting the virtual environment is as simple as deleting the 'venv' directory: ```shell $ rm -rf ./venv ``` Make sure to deactivate the virtualenv before deleting it. ## Further reading - [Python docs - venv](https://docs.python.org/3/library/venv.html). - [Stack Overflow discussion on the topic](https://stackoverflow.com/questions/41573587/what-is-the-difference-between-venv-pyvenv-pyenv-virtualenv-virtualenvwrappe). - [Why you should use python -m pip](https://snarky.ca/why-you-should-use-python-m-pip/).

Read on rspk.org

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.