Page 248 - Asterisk™: The Future of Telephony
P. 248
found he could write a quick Perl script to help his young daughter improve her math
skills.
Since we’ve already written a Perl program using AGI, and Ed has already written the
math program in Perl, we figured we’d take a stab at it in Python!
Let’s go through our Python script:
#!/usr/bin/python
This line tells the system to run this script in the Python interpreter. For small scripts,
you may consider adding the -u option to this line, which will run Python in unbuffered
mode. This is not recommended, however, for larger or frequently used AGI scripts,
as it can affect system performance.
import sys
import re
import time
import random
Here, we import several libraries that we’ll be using in our AGI script.
# Read and ignore AGI environment (read until blank line)
env = {}
tests = 0;
while 1:
line = sys.stdin.readline().strip()
if line == '':
break
key,data = line.split(':')
if key[:4] <> 'agi_':
#skip input that doesn't begin with agi_
sys.stderr.write("Did not work!\n");
sys.stderr.flush()
continue
key = key.strip()
data = data.strip()
if key <> '':
env[key] = data
sys.stderr.write("AGI Environment Dump:\n");
sys.stderr.flush()
for key in env.keys():
sys.stderr.write(" -- %s = %s\n" % (key, env[key]))
sys.stderr.flush()
This section of code reads in the variables that are passed to our script from Asterisk,
and saves them into a dictionary named env. These values are then written to STDERR
for debugging purposes.
def checkresult (params):
params = params.rstrip()
if re.search('^200',params):
220 | Chapter 9: The Asterisk Gateway Interface (AGI)