Writing AGI Scripts in Python
The AGI script we’ll be writing in Python , called “The Subtraction Game,” was inspired by a Perl program written by Ed Guy and discussed by him at the 2004 AstriCon conference. Ed described his enthusiasm for the power and simplicity of Asterisk when he 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])) ...
Get Asterisk: The Future of Telephony now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.