我正在尝试通过我定义的记录器获取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的响应。有没有办法我也可以通过记录器记录pexpect响应

下面是输出
2018-06-15 13:22:49,610 - foo - INFO - Hello before pexpect
2018-06-15 13:22:52,668 - foo - INFO - ls

等待回应

最佳答案

除非您阅读或期望,否则不会打印该文本。当使用期望值时,将填充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?

关于python - 无法通过python记录器打印pexpect响应,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50871258/

10-12 23:15