skyork
skyork

Reputation: 7411

How to activate a specifically named virtualenv using pipenv?

I created a specifically named virtualenv by setting PIPENV_CUSTOM_VENV_NAME before doing pipenv shell as outlined in this Github issue thread on "How to set the full name of the virtualenv created".

I can confirm a virtualenv with the name given exists in /Users/username/.local/share/virtualenvs/.

Now, how do I activate this specific virtualenv again? Doing pipenv shell in the project directory simply creates a new one, so how do I activate the one with a given name?

Upvotes: 2

Views: 4509

Answers (1)

Gino Mempin
Gino Mempin

Reputation: 29698

You will have to always export that PIPENV_CUSTOM_VENV_NAME environment variable.

It's the same as what that contributor did in that Github issue thread:

export PIPENV_CUSTOM_VENV_NAME=mycustomname  
pipenv install  
pipenv shell  
etc. etc. 

The export link sets that environment variable for all subsequent pipenv commands, and this includes activation of the environment:

# There is no virtual env yet
# ---

myapp$ PIPENV_CUSTOM_VENV_NAME=foo python3.8 -m pipenv --venv
No virtualenv has been created for this project(/path/to/myapp) yet!
Aborted!

# Let's create one named `foo` !
# ---

myapp$ PIPENV_CUSTOM_VENV_NAME=foo python3.8 -m pipenv install
Creating a virtualenv for this project...
Pipfile: /path/to/myapp/Pipfile
Using /usr/local/bin/python3 (3.10.8) to create virtualenv...
⠹ Creating virtual environment...created virtual environment 
...

Virtualenv location: /path/to/.venvs/foo

# There is now a virtual env !
# ---

myapp$ PIPENV_CUSTOM_VENV_NAME=foo python3.8 -m pipenv --venv
/path/to/.venvs/foo

# Let's activate it !
# ---

myapp$ PIPENV_CUSTOM_VENV_NAME=foo python3.8 -m pipenv shell
Launching subshell in virtual environment...
myapp$  . /path/to/.venvs/foo/bin/activate
(myapp) myapp$

# Let's check if it's really installing packages in the right place...
# ---

(myapp) myapp$ pipenv install flask
...
(myapp) myapp$ find ~/.venvs/foo/lib/python3.10/site-packages -name flask
/path/to/.venvs/foo/lib/python3.10/site-packages/flask

Now, this is a bit inconvenient. But you can define it per project in your .env file, as per the docs https://pipenv.pypa.io/en/latest/advanced/#virtual-environment-name

The logical place to specify this would be in a user’s .env file in the root of the project, which gets loaded by pipenv when it is invoked.

So, in your project, create a .env file, and define it there:

myapp$ cat .env
PIPENV_CUSTOM_VENV_NAME=foo

So now every time you run pipenv shell in that folder, pipenv would read your .env file in that same folder, and apply PIPENV_CUSTOM_VENV_NAME:

myapp$ cat .env
PIPENV_CUSTOM_VENV_NAME=foo

myapp$ python3.10 -m pipenv shell
Loading .env environment variables...
Loading .env environment variables...
Launching subshell in virtual environment...
myapp$  . /path/to/.venvs/foo/bin/activate

Upvotes: 4

Related Questions