Thursday, 28 June 2018

Not able to print pexpect response via python logger

I am trying to have pexepct stdout logs via logger that I have defined. Below is the code

import logging
import pexpect
import re
import time
# 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
logger.info("Hello before pexpect")
p = pexpect.spawn('telnet someIP')
p.logfile=logger
time.sleep(3)
p.sendline('ls')
logger.info("After pexpect")

With above code, logger is printing what pexepct is sending commands on the console but I am not getting response of pexpect. Is there a way I can log pexpect response too via logger

Below is the output

2018-06-15 13:22:49,610 - foo - INFO - Hello before pexpect
2018-06-15 13:22:52,668 - foo - INFO - ls

Waiting for response



from Not able to print pexpect response via python logger

No comments:

Post a Comment