Saturday, 4 October 2014

Experiments with Pexpect

The Pexpect python module is used to start up and control new processes from python code.  For the Manchester CoderDojo I needed to incrementally get output from a spawned process over the course of a long run.  To test this I created a simple module that counted to 20 slowly:


"""
Count to 20 in one second steps
"""
from time import sleep

for i in range(1,21):
    print(str(i))
    sleep(1)

Next I created a python module to spawn off a process to call the counter and print the output.

"""
Call the slow-running counter and print the results.
"""

import pexpect

output = pexpect.run('python count-slow.py')
print(output)

The problem of course is that the run command blocks until all the output is produced.  The solution allowing you to  see the output as it appears is to use the pexpect.spawn() function.  This function to creates a sub-process object from which you can read one line at a time.  Pyexpect.readline() will block until it receives a line.  An empty string indicates the process has completed.

"""
Call the slow-running counter and print the results.
"""

import pexpect

child = pexpect.spawn('python count-slow.py')
next_line = child.readline()
while next_line != '':
    print(next_line.strip())
    next_line = child.readline()

No comments: