Antoine Pinsard Antoine Pinsard - 1 year ago 153
Bash Question

Tmux split window and activate a python virtualenv

My favorite python developement environment is:

  • One large left pan for vim

  • Two small pans on the right for interactive consoles

Each pan shoud run a python virtualenv (using virtualenvwrapper). So here is the list of commands I have to type to setup my environment:

➜ ~ workon some_env
➜ ~ tmux splitw -h -l90
➜ ~ workon some_env
➜ ~ tmux splitw -v -p50
➜ ~ workon some_env

Putting these commands in a script and sourcing the file would unfortunately run
workon some_env
three times on the same pan rather than once on each pan.

Pretty simple, but pretty boring to type each time I want to setup a working environment.

I bound a shortcut to split the window correcty:

bind a source-file ~/.config/tmux/dev-session

This file

splitw -h -l90
splitw -v -p50

However, I'm unable to automatically run
workon some_env
on each pan. I turned the problem in every way, I just can't get it work.

splitw "workon some_env"
# Exits immediately as `workon` function terminates

splitw "echo 'workon some_env' | source /dev/stdin"
# Exits immediately as `source` terminates

splitw "workon_args=some_env zsh -f .some_custom_zshrc"
# Where .some_custom_zshrc contains:
# workon $workon_args
# Does not work since running `workon some_env` from a script
# has no effect on the script caller

splitw "zsh -c 'workon some_env' -i"
# `workon some_env` seems to be executed in a separate environment
# and the virtualenv is no more activated within the interactive shell

I tried even more exotic things, but here I'm stuck.

Answer Source

First create all of your panes.

Use send-keys to write your commands into the specified pane and execute them using C-m. For example:

tmux send-keys -t development:0.1 "workon some_env" C-m

If you have three panes, then the second and third would be SESSION_NAME:0.1 and SESSION_NAME:0.2

Here is an example of my configuration:

tmux new-session -s development -n editor -d

tmux split-window -h -t development

tmux select-pane -t development:0.1

tmux split-window -v -t development

tmux send-keys -t development:0.0 "emacs -nw" C-m

tmux send-keys -t development:0.0 f8

tmux send-keys -t development:0.1 "ptpython" C-m

This book has a great chapter on setting up environments using Tmux.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download