Package gavo :: Package svcs :: Module runner
[frames] | no frames]

Source Code for Module gavo.svcs.runner

 1  """ 
 2  Methods and classes to run programs described through DataDescriptors 
 3  within a twisted event loop. 
 4  """ 
 5   
 6  #c Copyright 2008-2019, the GAVO project 
 7  #c 
 8  #c This program is free software, covered by the GNU GPL.  See the 
 9  #c COPYING file in the source distribution. 
10   
11   
12  import sys 
13  import os 
14   
15  from twisted.internet import protocol 
16  from twisted.internet import reactor  
17  from twisted.internet import defer 
18  from gavo import base 
19   
20   
21 -class RunnerError(base.Error):
22 pass
23 24
25 -class StdioProtocol(protocol.ProcessProtocol):
26 """is a simple program protocol that writes input to the process and 27 sends the output to the deferred result in one swoop when done. 28 """
29 - def __init__(self, input, result, swallowStderr=False):
30 self.input, self.result = input, result 31 self.swallowStderr = swallowStderr 32 self.dataReceived = []
33
34 - def connectionMade(self):
35 self.transport.write(self.input) 36 self.transport.closeStdin()
37
38 - def outReceived(self, data):
39 self.dataReceived.append(data)
40
41 - def errReceived(self, data):
42 if not self.swallowStderr: 43 sys.stderr.write(data)
44
45 - def processEnded(self, status):
46 if status.value.exitCode!=0: 47 self.result.errback(status) 48 else: 49 self.result.callback("".join(self.dataReceived))
50 51
52 -def runWithData(prog, inputString, args, swallowStderr=False):
53 """returns a deferred firing the complete result of running prog with 54 args and inputString. 55 """ 56 result = defer.Deferred() 57 fetchOutputProtocol = StdioProtocol(inputString, result, swallowStderr) 58 prog = base.getBinaryName(prog) 59 reactor.spawnProcess(fetchOutputProtocol, prog, 60 args=[str(prog)]+list(str(s) for s in args), path=os.path.dirname(prog)) 61 return result
62