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
The text is not printed until you read or expect it. When you use expected you get p.after
and p.before
populated
p.sendline('ls')
logger.info("After pexpect")
p.read()
See below thread also
How to see the output in pexpect?
How can I send single ssh command to get result string with pexpect?
If you just want to output all display message of pexpect, try this:
LOG_FILE = open("logfile.log", "w+")
p = pexpect.spawn('telnet someIP')
p.logfile = LOG_FILE
p.sendline('ls')
Then, you will see all contents in LOG_FILE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With