Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "source" create or activate in the virtual environment?

Tags:

virtualenv

I'm brand new to Python, using terminal, pip and virtual environment.

From what I gather, the command 'source' activates the virtual environment and anything you do after that stays in the virtual environment, like installing something with pip installs it only in your virtual environment. However, do I need to actually create a folder or choose a location first before I run source? In other words, does source create the virtual environment or only activate one that already exists?

This stuff is really hard to wrap my head around. I think one of the things that is hindering my development is that I'm not familiar with certain directory structures like bin, etc.

like image 443
david Avatar asked May 02 '26 00:05

david


2 Answers

Once you create a virtualenv, you will see source created in the directory. You must cd to that particular source and do source activate to start working on that particular virtualenv. Each virtualenv has its own source.

You can also use virtualenv wrapper to make things easier.

like image 199
Joohwan Avatar answered May 05 '26 10:05

Joohwan


One extra thing to note:

source is actually completely unrelated to Python

See here: https://superuser.com/questions/46139/what-does-source-do

Running source activate in a terminal means in that same terminal it will run the contents of the file activate.

If you want, you can look at the contents of the file activate . You will see that the main thing it does is take the value of your $PATH environment variable, save a copy (to reuse later), and then update your $PATH environment variable for that terminal by adding the directory path to your venv at the BEGINNING of the $PATH environment variable:

Simple example:
$PATH before running activate: "/home/abc/bin:/usr/bin"
$PATH after running activate: "/home/abc/python-project/venv/bin:/home/abc/bin:/usr/bin"

This means, when you run python it first looks in this v/home/.../venv/bin directory for the python interpreter, which it finds and uses. Then when you run deactivate it resets your $PATH environment variable to the original value (the copy it saved earlier)

So it is not source that activates the virtual environment, but activate. source only means it is run in your current terminal.

like image 30
Anna Avatar answered May 05 '26 08:05

Anna