forked from wuub/SublimeREPL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repl.py
83 lines (68 loc) · 2.51 KB
/
repl.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
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Wojciech Bederski (wuub.net)
# All rights reserved.
# See LICENSE.txt for details.
from uuid import uuid4
from codecs import getincrementaldecoder, getencoder
class NoReplError(LookupError):
"""Looking for Repl subclass failed"""
pass
class Repl(object):
"""Class that represents a process that is being executed.
For example this can be python, bash or a telnet session"""
TYPE = "<base>"
@classmethod
def subclass(cls, type):
"""Returns subclass of Repl of given type eq. SubprocessRepl"""
todo = [cls]
seen = set()
while True:
if not todo:
raise NoReplError
cur = todo.pop()
if cur in seen:
continue
if cur.TYPE == type:
return cur
todo.extend(cur.__subclasses__())
def __init__(self, encoding, external_id=None, cmd_postfix="\n", suppress_echo=False):
self.id = uuid4().hex
self.decoder = getincrementaldecoder(encoding)()
self.encoder = getencoder(encoding)
self.external_id = external_id
self.cmd_postfix = cmd_postfix
self.suppress_echo = suppress_echo
def close(self):
if self.is_alive():
self.kill()
def name(self):
"""Returns name of this repl that should be used as a filename"""
return NotImplementedError
def is_alive(self):
""" Returns true if the undelying process is stil working"""
raise NotImplementedError
def write_bytes(self, bytes):
raise NotImplementedError
def read_bytes(self):
"""Reads at lest one byte of Repl output. Returns None if output died.
Can block!!!"""
raise NotImplementedError
def kill(self):
"""Kills the underlying repl"""
raise NotImplementedError
def write(self, command):
"""Encodes and evaluates a given command"""
(bytes, how_many) = self.encoder(command)
return self.write_bytes(bytes)
def read(self):
"""Reads at least one decoded char of output"""
while True:
bs = self.read_bytes()
if not bs:
return None
try:
output = self.decoder.decode(bs)
except Exception, e:
output = "[SublimeRepl: decode error]\n"
if output:
return output