Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to activate virtual environment when using venv

Using Python 3.7.0 on Mac. Trying to use venv module that was added post python 3.4.

I setup my virtual env using python3 venv -m path/to/my/dir - my question is do I need to activate this virtual env to use?

The documentation seem to imply I don't need to?

You don’t specifically need to activate an environment; activation just prepends the virtual environment’s binary directory to your path, so that “python” invokes the virtual environment’s Python interpreter and you can run installed scripts without having to use their full path. However, all scripts installed in a virtual environment should be runnable without activating it, and run with the virtual environment’s Python automatically.

If I don't have to activate, what is the benefit of prepending venv to binary directory? Wouldn't this have to happen regardless for a venv to work?

like image 628
azochz Avatar asked Dec 24 '22 06:12

azochz


1 Answers

Activating the virtualenv gives you convenience. It is never required.

Even for scripts that are configured to run with #!/usr/bin/env python, (which looks up the python executable on your path), you could manually update the PATH environment variable:

$ PATH="/path/to/venv/bin" some_script

Activating makes the PATH update stick until you deactivate again, and that can be convenient.

For example, I regularly have several virtualenvs in use at any one time. Some of them are there only to install some command-line tools I have symlinked into my ~/bin/ directory, another is home to a Jupyter notebook, and 2 more are used to quickly verify code snippets in different Python versions with access to 3rd-party libraries. I don't activate any of those.

When you don’t activate a virtualenv, all that happens is that your terminal PATH variable is not updated to put the bin directory of the virtualenv first, so when you enter python or pip or other script without any path into the terminal, the shell will find a different Python binary to run. You can always use any of the commands in the virtualenv bin/ directory by giving the full path to that command.

like image 127
Martijn Pieters Avatar answered Dec 25 '22 19:12

Martijn Pieters