-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtmux.py
executable file
·126 lines (91 loc) · 2.88 KB
/
tmux.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env python3
# encoding: utf-8
import subprocess
import argparse
import sys
class Tmux:
"""Wrapper class around tmux that returns more helpful codes.
Returns:
0 if tmux detached.
2 if tmux exited
tmux return code otherwise
"""
def __init__(self):
pass
def new(self, session_name):
"""make a new session on the specified host
:session_name: TODO
:returns: TODO
"""
cmd = ['tmux',
'new-session',
'-s',
session_name]
return self._exec_tmux_cmd(cmd)
def attach(self, session_name=None):
"""attach to an existing session
:session_name: TODO
:returns: TODO
"""
cmd = ['tmux', 'attach']
if session_name:
cmd.extend(['-t', session_name])
return self._exec_tmux_cmd(cmd)
def rename(self, old, new):
"""rename a session
:old: TODO
:new: TODO
:returns: TODO
"""
cmd = ['tmux',
'rename-session',
'-t',
old,
new]
return self._exec_tmux_cmd(cmd)
def kill(self, session_name):
"""kill an existing session
:session_name: TODO
:returns: TODO
"""
cmd = ['tmux',
'kill-session',
'-t',
session_name]
return self._exec_tmux_cmd(cmd)
def _exec_tmux_cmd(self, cmd):
"""executes tmux cmd and returns a code dependent on the result
:type cmd: str
"""
try:
tmux_output = subprocess.check_output(cmd)
print(tmux_output.decode())
if tmux_output.find(b'detached') >= 0:
return 100
elif tmux_output.find(b'exited') >= 0:
return 200
else:
return 0
except subprocess.CalledProcessError as e:
print(e.output.decode(), end='')
return e.returncode
def main():
# parse args
parser = argparse.ArgumentParser(description="A wrapper around Tmux providing some basic functionality"
"and more useful return codes")
parser.add_argument('action', choices=('new', 'attach', 'rename', 'kill'),
help='The action to make tmux perform')
parser.add_argument('name', help='The name of the target session')
parser.add_argument('--new_name', help='specify new name for session. Ignored unless ACTION is "rename"')
args = parser.parse_args()
# execute tmux stuff
tmux = Tmux()
if args.action == 'rename':
retval = tmux.rename(args.name, args.new_name)
else:
method = getattr(tmux, args.action)
retval = method(args.name)
#print('tmux.py retuned: {}'.format(retval))
sys.exit(retval)
if __name__ == '__main__':
main()