pexpect and logging integration

Jean-Michel Pichavant jeanmichel at
Wed Mar 10 15:07:57 CET 2010

Lars Stavholm wrote:
> Hi all,
> has anyone managed to integrate pexpect and logging?
> I.e., I'd like to be able to pick up the dialog,
> commands sent and responses received, in my logging.
> I know about the pexpect logfile, and I can log things
> to stdout or stderr, but I really need to log using the
> python logging library.
> Any thoughts appreciated
> /Lars
I had to implement this.
It's a bit of a hack, but it does the job.

The following code is tested with python 2.5, I remember pexpect behaves 
slightly differently in python 2.3.

import logging
import pexpect
import re

# this will be the method called by the pexpect object to log
def _write(*args, **kwargs):
    content = args[0]
    # let's ignore other params, pexpect only use one arg AFAIK
    if content in [' ', '', '\n', '\r', '\r\n']:
        return # don't log empty lines
    for eol in ['\r\n', '\r', '\n']:
        # remove ending EOL, the logger will add it anyway
        content = re.sub('\%s$' % eol, '', content)
    return # call the logger info method with the 
reworked content

# our flush method
def _doNothing():

# get the logger
logger = logging.getLogger('foo')

# configure the logger
logger.handlers[-1].setFormatter(logging.Formatter("%(asctime)s - 
%(name)s - %(levelname)s - %(message)s"))

# give the logger the methods required by pexpect
logger.write = _write
logger.flush = _doNothing

p = pexpect.spawn('echo "hello world !!"', logfile=logger)

... 2010-03-10 15:01:31,234 - foo - INFO - hello world !!

Hope it helps.


More information about the Python-list mailing list