Nit*_*esh 12 python pexpect python-2.7 python-3.x
我试图通过我已经定义的记录器获得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")
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,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
Run Code Online (Sandbox Code Playgroud)
等待答复
在您阅读或期望之前,不会打印文本.当您使用预期时,您将获得p.after并p.before填充
p.sendline('ls')
logger.info("After pexpect")
p.read()
Run Code Online (Sandbox Code Playgroud)
另见下面的线程
如何发送单个ssh命令来获取带有pexpect的结果字符串?
| 归档时间: |
|
| 查看次数: |
289 次 |
| 最近记录: |