Tuesday, August 04, 2009

Automate interactive script with pyexpect

Sometime it is actually nice that automate interactive script, aka the one that need user to input something to continue. Such as django manage.py script

So I found pexpect, it is a python version of expect, which does that.

For example to use with reset the database in django:
import sys
import pexpect
#call the commands
result = pexpect.spawn("python manage.py reset_db")
#tell it to expect what should shows
result.expect("Type 'yes' to continue, or 'no' to cancel")
#send the results

Actually you can use it to run programs. Without the expect methods or sendline. The program will just runs
import sys
import pexpect
#just run the command

commands = pexpect.spawn("ls -a")
print commands

BTW, do check expect, it is the one that runs without python. Which is what  pexpect based on. Either way, it should be available to any linux distro. On ubuntu find expect and pexpect on synation, it is there.

No comments:

Post a Comment