[英]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")
使用上面的代碼,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
等待答復
在您閱讀或期望之前,不會打印文本。 當你使用預期時,你會得到p.after
和p.before
填充
p.sendline('ls')
logger.info("After pexpect")
p.read()
另見下面的線程
如果您只想輸出pexpect的所有顯示消息,請嘗試以下操作:
LOG_FILE = open("logfile.log", "w+")
p = pexpect.spawn('telnet someIP')
p.logfile = LOG_FILE
p.sendline('ls')
然后,您將看到LOG_FILE中的所有內容
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.