无法通过 python 记录器打印预期响应

Not able to print pexpect response via python logger

我正在尝试通过我定义的记录器获取 pexepct stdout 日志。下面是代码

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")

使用上面的代码,记录器正在打印 pexepct 在控制台上发送的命令,但我没有收到 pexpect 的响应。有没有办法我也可以通过 logger

记录预期响应

下面是输出

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

等待回复

直到您阅读或期望文本才会打印出来。当您使用 expected 时,您会得到 p.afterp.before populated

p.sendline('ls')
logger.info("After pexpect")
p.read()

另请参阅下面的线程

How to see the output in pexpect?

How can I send single ssh command to get result string with pexpect?

如果你只想输出预期的所有显示信息,试试这个:

LOG_FILE = open("logfile.log", "w+")
p = pexpect.spawn('telnet someIP')
p.logfile = LOG_FILE
p.sendline('ls')

然后,您将看到LOG_FILE

中的所有内容