Monday, November 15, 2021

[SOLVED] How to activate a python virtualenv using a bash script and keep it after the script finishing?

Issue

I've created a new python venv as usual: python -m venv .venv

I need to create a bash script which can activate this venv and keep that state after finishing.

I know, that a normal solution to activate a venv is calling source .venv/bin/activate from terminal or using it via an alias.

But I need this feature in my bash script which does a lot of other useful things for my development.

I tried to do it in a simple way:

my-script.sh:

#!/bin/bash

source ".venv/bin/activate"
echo $VIRTUAL_ENV

When the script is running, the venv is activated, I check it via $VIRTUAL_ENV. But after finishing, the state is lost:

max@mbp t3 $ ./my-script.sh
/Users/max/t3/.venv
max@mbp t3 $ echo $VIRTUAL_ENV

max@mbp t3 $

Is it possible to keep an activated venv after finishing the script?

I need it for my script p which has a lot off different helping commands for python, pip, twine, etc.

I want to be able to do such a thing vith my script p and venv:

$ p v

1) If there is already activated venv, do nothing

2) If there is a .venv folder, activate the venv and return ACTIVATED venv bash prompt.

3) If there is no .venv folder, first create venv and next activate it. And also return ACTIVATED venv bash prompt.


Solution

no you cannot do that because when you run your script like that it runs every thing in a subshell that is destroyed when done

... but its easy to

source ./my-script.sh which will not create a new subshell to run it in

(or the more common alias . ./my-script.sh)



Answered By - Joran Beasley