forked from kenjyoung/KHex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
program.py
80 lines (68 loc) · 2.32 KB
/
program.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
#----------------------------------------------------------------------------
# Opens connection to GTP program.
#----------------------------------------------------------------------------
import string, os, sys, subprocess
from subprocess import Popen, PIPE
#----------------------------------------------------------------------------
class Program:
class CommandDenied(Exception):
pass
class Died(Exception):
pass
def __init__(self, command, verbose):
self._command = command
self._verbose = verbose
if self._verbose:
print ("Creating program: "+command)
#self._stdin, self._stdout, self._stderr = subprocess.os.popen3(command)
p = Popen(command, shell = True, stdin=PIPE, stdout=PIPE,
stderr=PIPE, close_fds=True, universal_newlines=True)
self._stdin, self._stdout, self._stderr = (p.stdin, p.stdout, p.stderr)
self._isDead = 0
def getCommand(self):
return self._command
def getDenyReason(self):
return self._denyReason
def getName(self):
name = "?"
try:
name = self.sendCommand("name").strip()
version = self.sendCommand("version").strip()
name += " " + version
except Program.CommandDenied:
pass
return name
def isDead(self):
return self._isDead
def sendCommand(self, cmd):
try:
if self._verbose:
print("< " + cmd)
self._stdin.write(cmd + "\n")
self._stdin.flush()
return self._getAnswer()
except IOError:
self._programDied()
def _getAnswer(self):
answer = ""
done = 0
numberLines = 0
while not done:
line = self._stdout.readline()
if line == "":
self._programDied()
if self._verbose:
sys.stdout.write("> " + line)
numberLines += 1
done = (line == "\n")
if not done:
answer += line
if answer[0] != '=':
self._denyReason = answer[2:].strip()
raise Program.CommandDenied
if numberLines == 1:
return answer[1:].strip()
return answer[2:]
def _programDied(self):
self._isDead = 1
raise Program.Died