lots of updates, amongst others:
[saartuer.git] / tyshell
1 #!/usr/bin/python3
2 import os
3 import readline
4 import shlex
5 import sys
6 import subprocess
7 import socket
8
9 tuerSock = "/run/tuer.sock"
10
11 # use a histfile
12 histfile = os.path.join(os.path.expanduser("~"), ".tyshellhist")
13 try:
14     readline.read_history_file(histfile)
15 except IOError:
16     pass
17 import atexit
18 atexit.register(readline.write_history_file, histfile)
19 atexit.register(print, "Bye")
20
21 # available commands
22 def helpcmd(c):
23         print("Available commands: %s" % ", ".join(sorted(commands.keys())))
24
25 def extcmd(cmd):
26         def run(c):
27                 ret = subprocess.call(cmd)
28                 if ret != 0:
29                         print("Command returned non-zero exit statis %d" % ret)
30         return run
31
32 def sendcmd(addr, cmd):
33         def run(c):
34                 print("Running %s..." % (cmd))
35                 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
36                 s.connect(addr)
37                 s.send(cmd.encode())
38                 data = s.recv(4)
39                 s.close()
40                 print("...done")
41                 if data != b'1':
42                         print("Received unexpected answer %s" % str(data))
43         return run
44
45 def exitcmd(c):
46         sys.exit(0)
47
48 commands = {
49         'exit': exitcmd,
50         'help': helpcmd,
51         'open': sendcmd(tuerSock, 'open'),
52         'close': sendcmd(tuerSock, 'close'),
53         'buzz': sendcmd(tuerSock, 'buzz'),
54 }
55
56 # input loop
57 print("Welcome to tyshell. Use help to see what you can do.")
58 while True:
59         try:
60                 command = input("$ ")
61         except EOFError:
62                 print()
63                 break
64         command = shlex.split(command)
65         if not len(command): continue
66         # execute command
67         if command[0] in commands:
68                 try:
69                         commands[command[0]](command)
70                 except Exception as e:
71                         print("Error while executing %s: %s" % (command[0], str(e)))
72         else:
73                 print("Command %s not found. Use help." % command[0])
74