0x01 简介

libtmux是一个封装了一系列tmux操作的python库,部分指令支持的不是很好。如果有需求但是library中没有实现,可以看看源码自己实现。repo:https://github.com/tmux-python/libtmux

使用之后我发现这只是一个半成品的library,功能上不如直接用bash script来操作tmux来的方便,不过还是具有很好的学习价值。

如果想要直接在bash中创建一个2*2的窗口,可以使用:

tmux new-window \; split-window -h \; split-window -f \; split-window -h

0x02 show me the code

批量创建 window 和 panel 的 python脚本如下。

#!/usr/bin/env python3
# coding=utf-8
# author: thinkycx
# date: 2018-01-11
# Usage:
#    run several commands in tmux panel, every window have 4 panes
#    $ pip3 install libtmux
#    $ python tmux.py
 
 
import libtmux
import math
import os
import logging
 
def create_session(session_name, commands):
    '''
        create session with 2*2 panes and run commands
    :param session_name: tmux session name
    :param commands: bash commands
    :return:
    '''
    logging.info(commands)
    # pane_NUM = 3
    # WINDOW_NUM = int(math.ceil(len(commands)/4.0))  # in python3, we can use 4 also
 
    server = libtmux.Server()
    session = server.new_session(session_name)
 
    # create windows
    windows = []
    panes = []
 
    for i in range(len(commands)):
        # create window to store 4 panes
        if i % 4 == 0:
            win = session.new_window(attach=False, window_name="win"+str(int(i/4)))
            windows.append(win)
 
            # tmux_args = ('-h',)
            win.cmd('split-window', '-h')
            win.cmd('split-window', '-f')
            win.cmd('split-window', '-h')
 
            panes.extend(win.list_panes())
 
        panes[i].send_keys(commands[i])
 
    logging.info(panes)
    logging.info(windows)
 
 
if __name__ == '__main__':
    commands = []
    for i in range(10):
        commands.append("echo " + str(i))
 
    os.system("tmux kill-session -t session")
    create_session("session", commands)

0x03 效果