Targeting specific terminal emulators
Automatically running a command on creation of a new terminal tab would be a feature of the specific terminal you are using, and not related to python
or virtualenv
.
To have a broader range or answers the question would probably have to be How to autorun a shell command for terminal emulator xyz. For example, for gnome-terminal
you can use custom profiles as described in https://unix.stackexchange.com/a/3856/15312, but this is an unportable solution if you decide to switch to another terminal or platform.
On the other hand, nobody wants to get locked to a specific terminal app, therefore the next option would be a more portable approach.
Targeting shell init scripts
If you control the shell that is running in the tab, then you can do it in your shell init script.
For example, for bash
you can add the following lines in your ~/.bashrc
script:
if [[ -f .venv/bin/activate ]] ; then
source .venv/bin/activate
fi
For zsh
add the snippet to ~/.zshrc
.
Whenever you create a new shell or open a new tab this snippet will check if you have a .venv
folder in the current path and activate that venv automatically. If you create your virtualenvs in a folder which is not named .venv
then adjust the script accordingly.
You might also want to override cd
so that whenever you cd
into a venv it will be automatically activated:
Below is an example for zsh
:
function cd() {
builtin cd $1
if [[ -f .venv/bin/activate ]] ; then
source .venv/bin/activate
fi
}
Reduce typing with virtualenvwrapper
Specifically regarding virtualenv
: you might want to try virtualenvwrapper which can help reduce the amount of typing, and make managing environments easier by providing autocompletion for virtualenv folders.
Backgrounding processes
And finally, as a quick workaround, instead of creating new tabs with the same env, you can suspend a currently running process (such as manage.py runserver
) with Ctr+z, optionally run bg
to resume it in background if you want to keep it running, then edit and save a file, and bring the original process back to foreground with fg
. See this for more details.
nano ~/.bash_aliases && source ~/.bash_aliases
to create & activate one, then pastealias X='virtualenv $PWD/bin/activate'
(change 'X' to be whatever you prefer, like 've'). – Tom Brossman Jun 25 '16 at 16:59