如何在pexpect的logfile中获取时间戳

时间:2012-11-07 14:24:36

标签: python python-2.7 pexpect

我正在使用 pexpect 来处理我的telnet和ssh通信。 我还在日志文件中编写所有请求/响应。使用pexpect.logfile(filename)

我想在日志文件中也有时间戳。 我在文档中的任何地方都找不到它!有没有人知道如何实现这个功能?

3 个答案:

答案 0 :(得分:5)

logfile可以是具有write()flush()方法的任何对象:

from datetime import datetime

class TimestampedFile(object):
    def __init__(self, file):
        self.file = file

    def write(self, data):
        # .. filter data however you like
        ts = datetime.utcnow().isoformat()  # generate timestamp
        return self.file.write("%s %s\n" % (ts, data))  # write to original file

    def flush(self):
        self.file.flush()

实施例

with open(filename, 'w') as file:
    pexpect.run('echo "hello world!"', logfile=TimestampedFile(file))    

Your logging example可以简化:

class FileAdapter(object):
    def __init__(self, logger):
        self.logger = logger
    def write(self, data):
        # NOTE: data can be a partial line, multiple lines
        data = data.strip() # ignore leading/trailing whitespace
        if data: # non-blank
           self.logger.info(data)
    def flush(self):
        pass  # leave it to logging to flush properly

实施例

# setup logging to include a timestamp
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.INFO)
# ... run command sometime later
pexpect.run('echo "hello world!"', logfile=FileAdapter(logging.getLogger('foo')))

答案 1 :(得分:1)

如果您查看pexpect.py源文件,您会看到记录所采用的方法只是将发送/接收到子进程的内容写入流(可以是文件或例如,如果您希望登录控制台,则sys.stdout。因此,在不更改pexpect源的情况下,您所要求的是不可能的,例如,能够使用标准库logging模块记录器进行输出(提示:可能是一个很好的机会来为突出?)。

答案 2 :(得分:1)

经过一番搜索,我发现以下代码对我有用! 看看下面的代码:

import logging
import pexpect
import re

# this is the method called by the pexpect object to log
def _write(*args, **kwargs):
    content = args[0]
    # Ignore other params, pexpect only use one arg
    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

logger = logging.getLogger('foo')
hdlr = logging.FileHandler('/bar.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)

# give the logger the methods required by pexpect
logger.write = _write
logger.flush = _doNothing

p = pexpect.spawn('echo "hello world !"', logfile=logger)