34ef515cbc8bccb05476368efcafc23ba44f7d8a
[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("~"), ".pyshellhist")
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
20 # available commands
21 def help(c):
22         print("Available commands: %s" % ", ".join(sorted(commands.keys())))
23
24 def extcmd(cmd):
25         def run(c):
26                 ret = subprocess.call(cmd)
27                 if ret != 0:
28                         print("Command returned non-zero exit statis %d" % ret)
29         return run
30
31 def sendcmd(addr, cmd):
32         def run(c):
33                 print("Running %s..." % (cmd))
34                 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
35                 s.connect(addr)
36                 s.send(cmd.encode())
37                 data = s.recv(4)
38                 s.close()
39                 print("...done")
40                 if data != b'1':
41                         print("Received unexpected answer %s" % str(data))
42         return run
43
44 commands = {
45         'exit': None, # catched below, quits the loop
46         'help': help,
47         'open': sendcmd(tuerSock, 'open'),
48         'close': sendcmd(tuerSock, 'close'),
49         'buzz': sendcmd(tuerSock, 'buzz'),
50 }
51
52 # input loop
53 print("Welcome to tyshell. Use help to see what you can do.")
54 while True:
55         try:
56                 command = input("$ ")
57         except EOFError:
58                 print()
59                 break
60         command = shlex.split(command)
61         if not len(command): continue
62         # execute command
63         if command[0] == "exit":
64                 break
65         elif command[0] in commands:
66                 try:
67                         commands[command[0]](command)
68                 except Exception as e:
69                         print("Error while executing %s: %s" % (command[0], str(e)))
70         else:
71                 print("Command %s not found. Use help." % command[0])
72 print("Bye")