#!/usr/bin/python import sys,string class AGI: """ Class AGI facilitates writing AGI scripts in Python. Exported functions: Write(message): Writes message to Asterisk Console. Cmd(command): Send command to Asterisk, read result. The result is a two element tuple: [0] A text string giving the entire result returned by Asterisk [1] The "result=" integer extracted from the result line If we get an unhappy response from Asterisk or if the result returned to the right of the equals sign is not an integer we issue an error message and terminate the script. Exported Variables: env Dictionary containing the various environment startup items, as passed to us by Asterisk. """ def Write(self,data): """ Write unbuffered line output to STDERR. Ensures data is flushed out. """ sys.stderr.write(str(data) + "\n") sys.stderr.flush() def Cmd(self,command): """ Send an AGI command to Asterisk; read back the response. The result is a two element tuple: [0] A text string giving the entire result returned by Asterisk [1] The "result=" integer extracted from the result line If we get an unhappy response from Asterisk or if the result returned to the right of the equals sign is not an integer we issue an error message and terminate the script. """ try: sys.stdout.write(str(command) + "\n") sys.stdout.flush() Response = sys.stdin.readline() if Response[:11] <> '200 result=': #we didn't get a happy response for AGI raise "AgiError" #accumulate integer portion J = 11 while J < len(Response) and (Response[J] in '0123456789'): J += 1 res = Response[11:J] try: ResInt = int(res) except ValueError: #there is no integer immediatly to the right of the equal sign raise "AgiError" except "AgiError": self.Error('Unexpected response to AGI command.') self.Error('Command: %s'%command) self.Error('Response: %s'%Response) self.Error('Script terminated.') sys.exit() return (Response,ResInt) def __init__(self): """ Read until blank line to get the AGI environment. The lines read are used to build the dictionary 'env'. """ self.env = {} while 1: line = string.strip(sys.stdin.readline()) if line == '': #blank line signals end break key,data = string.split(line,':') key = string.strip(key) data = string.strip(data) if key <> '': self.env[key] = data