Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python Virtual Environments with Terminator

With Terminator, a user can define layouts within the configuration file. With these layouts, the user can set a command to be executed at start-up. So, for example, one could create a layout in which a terminal automatically executed ls like this (note the bash command to avoid the terminal closing):

command = "ls; bash"

Now, how can I make Terminator load a Python Virtual Environment instead? Keeping, of course, the bash console active with the environment loaded.

Note

The trivial way:

command = "workon my_env; bash"

or its source my_env/bin/activate equivalent (without using virtualenvwrapper), wont work.

like image 422
Peque Avatar asked Jul 20 '15 19:07

Peque


People also ask

Which virtual environment is best for Python?

Two most popular virtual environment libraries for Python are venv and virtualenv. The difference between these two are negligible. However, there is one big difference and that is venv is a standard library that does not need to be installed while virtualenv needs to be installed with pip.

How do I run a Python project in a virtual environment?

To use the virtual environment you created to run Python scripts, simply invoke Python from the command line in the context where you activated it. For instance, to run a script, just run python myscript.py .

Does Python need virtual environment?

Virtual Environment should be used whenever you work on any Python based project. It is generally good to have one new virtual environment for every Python based project you work on. So the dependencies of every project are isolated from the system and each other.


1 Answers

The trick is to do everything with just "one" command: bash. Taking advantage of its -i option (interactive) and using a custom --rcfile in which PROMPT_COMMAND is set to whatever we want to execute. The result would be like this:

command = "bash --rcfile <(cat ${HOME}/.bashrc; echo 'export PROMPT_COMMAND="workon my_env; unset PROMPT_COMMAND"') -i"

Explanation

  • We execute bash in interactive (-i) mode.
  • We execute commands from a custom command file (--rcfile) instead of .bashrc.
  • This file is created with the contents of .bashrc plus one more command.
  • This extra command exports PROMPT_COMMAND with a value of "whatever we want to execute". In this case: workon my_env.
  • The PROMPT_COMMAND is unset just after it is executed the first time to avoid multiple executions after each interaction with the shell.

One could easily extend the custom command just editing the part workon my_env. So, for example, if you want to automatically execute ls appart from loading the Virtual Environment, you would write workon my_env; ls instead.

like image 188
Peque Avatar answered Sep 21 '22 01:09

Peque