Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

pexpect and logging integration

719 views
Skip to first unread message

Lars Stavholm

unread,
Mar 10, 2010, 12:31:19 AM3/10/10
to pytho...@python.org
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

Jean-Michel Pichavant

unread,
Mar 10, 2010, 9:07:57 AM3/10/10
to Lars Stavholm, pytho...@python.org
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 logger.info(content) # call the logger info method with the
reworked content


# our flush method
def _doNothing():
pass

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

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

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

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

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

Hope it helps.

JM

Lars Stavholm

unread,
Mar 11, 2010, 3:43:50 AM3/11/10
to Jean-Michel Pichavant, pytho...@python.org
It works like a charm, thank you!
/Lars
0 new messages