Reputation: 61
I was trying to invoke tmux and to control the tmux from the same python script. It's stuck in tmux process creation and never returns. How do I create the process (tmux)?
#!/usr/bin/python
import time
import sys
import os
import subprocess
class Tmux(object):
WAIT_SECS = 5
def __init__(self, session_name, param):
self.name = session_name
# os.system('tmux new -s %s &' % session_name)
subprocess.Popen(['/bin/bash', '-c', 'tmux new -s %s' % session_name])
# subprocess.check_call('tmux new -s %s' % session_name, shell=True, close_fds=True)
# ======NOT return here, unless exit from tmux==========
def execute(self, cmd, wait_secs=WAIT_SECS):
time.sleep(wait_secs)
os.system('tmux send-keys -t %s ls Enter' % self.name)
def horizontal_split(self):
time.sleep(1)
os.system('tmux split-window -v -t %s' % self.name)
if __name__ == '__main__':
print 'tmux test............'
tmux = Tmux("tmux-test", 999)
tmux.horizontal_split()
tmux.execute('ls')
Upvotes: 0
Views: 6872
Reputation: 2821
Module libtmux is perfect for your case, so you can manipulate tmux in Python directly. https://github.com/tony/libtmux
For example, you can do
import libtmux
server = libtmux.Server()
session = server.find_where({"session_name": "session_test"})
session = server.new_session(session_name="session_test", kill_session=True, attach=False)
window = session.new_window(attach=True, window_name="session_test")
pane1 = window.attached_pane
pane2 = window.split_window(vertical=False)
window.select_layout('even-horizontal')
pane1.send_keys('ls -al')
pane2.send_keys('ls -al')
server.attach_session(target_session="session_test")
Upvotes: 3
Reputation: 531175
Part of the problem is that you are attaching to the session as soon as you create it (which requires a terminal; perhaps that is why you are trying to run bash
rather than tmux
directly). You should be able to simply start the session with the -d
option to avoid attaching to it.
def __init__(self, session_name, param):
self.name = session_name
self.p = subprocess.Popen(['tmux', 'new', '-d', '-s', session_name])
You should also use subprocess
for the other methods instead of os.system
.
Upvotes: 2