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

时间:2018-06-15 07:50:06

标签: python python-3.x python-2.7 pexpect

我正在尝试通过我已定义的记录器获取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")

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

记录pexpect响应

以下是输出

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

等待回复

2 个答案:

答案 0 :(得分:5)

直到您阅读或期待该文本后,该文本才会被打印。使用预期值时,您将填充p.afterp.before

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?

答案 1 :(得分:1)

如果只想输出pexpect的所有显示消息,请尝试以下操作:

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

然后,您将在LOG_FILE中看到所有内容