Commit | Line | Data |
---|---|---|
f4de0bf1 FT |
1 | import sys, os, io, termios |
2 | ||
3 | class conv(object): | |
4 | msg_notice = 0 | |
5 | msg_info = 1 | |
6 | msg_debug = 2 | |
7 | ||
8 | def error(self, msg): | |
9 | pass | |
10 | def message(self, msg, level=0): | |
11 | pass | |
12 | def prompt(self, prompt, echo, default=None): | |
13 | return default | |
14 | ||
15 | class termconv(conv): | |
16 | def __init__(self, ifp, ofp): | |
17 | self.ifp = ifp | |
18 | self.ofp = ofp | |
19 | ||
20 | def error(self, msg): | |
21 | self.ofp.write("%s\n" % (msg,)) | |
22 | self.ofp.flush() | |
23 | def message(self, msg, level=0): | |
24 | if level <= self.msg_info: | |
25 | self.ofp.write("%s\n" % (msg,)) | |
26 | self.ofp.flush() | |
27 | def prompt(self, prompt, echo, default=None): | |
28 | if echo: | |
29 | self.ofp.write(prompt) | |
30 | self.ofp.flush() | |
31 | ret = self.ifp.readline() | |
32 | assert ret[-1] == '\n' | |
33 | return ret[:-1] | |
34 | else: | |
35 | attr = termios.tcgetattr(self.ifp.fileno()) | |
36 | bka = list(attr) | |
37 | try: | |
38 | attr[3] &= ~termios.ECHO | |
39 | termios.tcflush(self.ifp.fileno(), termios.TCIOFLUSH) | |
40 | termios.tcsetattr(self.ifp.fileno(), termios.TCSANOW, attr) | |
41 | self.ofp.write(prompt) | |
42 | self.ofp.flush() | |
43 | ret = self.ifp.readline() | |
44 | self.ofp.write("\n") | |
45 | assert ret[-1] == '\n' | |
46 | return ret[:-1] | |
47 | finally: | |
48 | termios.tcsetattr(self.ifp.fileno(), termios.TCSANOW, bka) | |
49 | ||
df72b1a5 | 50 | class ctermconv(termconv): |
f4de0bf1 | 51 | def __init__(self, fp): |
df72b1a5 | 52 | super().__init__(fp, fp) |
f4de0bf1 FT |
53 | self.cfp = fp |
54 | ||
55 | def close(self): | |
56 | self.cfp.close() | |
57 | def __enter__(self): | |
58 | return self | |
59 | def __exit__(self, *excinfo): | |
60 | self.close() | |
61 | return False | |
62 | ||
63 | null = conv() | |
64 | stdioconv = termconv(sys.stdin, sys.stdout) | |
65 | ||
66 | def ttyconv(): | |
df72b1a5 | 67 | return ctermconv(io.TextIOWrapper(io.FileIO(os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY), "r+"))) |
f4de0bf1 FT |
68 | |
69 | def default(): | |
70 | return null |