1

I am launching a new terminal on Ubuntu and want to activate a Python virtual environment once it opens. The virtual environment is normally activated by running:

source ./environment/bin/activate

where my virtual environment is called environment.

The command I'm using to do this is:

gnome-terminal --geometry 160x80+-26+4 --working-directory=/home/user/Work/project  -x bash -c "source /home/user/Work/project/environment/bin/activate; exec bash"

The path to the activate script is correct, but when I launch the terminal the virtual environment is not activated.

I suspect that's because source runs in one bash instance, but then exec bash creates a new one in order to keep the terminal open (just a hypothesis here).

How can I get the source command to affect that new terminal and leave it open?

Raffa
  • 32,237
Edy Bourne
  • 309
  • 2
  • 5
  • 13

1 Answers1

3

How can I get the source command to affect that new terminal and leave it open?

The more proper way of starting an interactive shell while sourcing your file of choice is by using the syntax bash --rcfile ...:

The --rcfile file option will force Bash to read and execute commands from file instead of ~/.bashrc.

Use it like so:

gnome-terminal --geometry 160x80+-26+4 \
--working-directory=/home/user/Work/project \
-- bash --rcfile /home/user/Work/project/environment/bin/activate

And you don't need to use -x(this option is deprecated), but use -- instead before the command.

The path to the activate script is correct, but when I launch the terminal the virtual environment is not activated.

Even though the prompt doesn't show as such, but your virtual environment was, most likely, activated nonetheless and you can verify that with e.g. which python3 which should point to the Python3 executable in your virtual environment directory.

I suspect that's because source runs in one bash instance, but then exec bash creates a new one in order to keep the terminal open (just a hypothesis here).

You are right, exec bash replaces the first(non-interactive shell) with another(interactive shell sourcing your ~/.bashrc) ... and you can patch that with:

gnome-terminal --geometry 160x80+-26+4 \
--working-directory=/home/user/Work/project \
-- bash -ic "source /home/user/Work/project/environment/bin/activate; exec bash --norc"
Raffa
  • 32,237