2

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

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

4

3 回答 3

6

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))    

您的日志记录示例可以简化:

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')))
于 2012-11-09T10:16:07.387 回答
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)
于 2012-11-08T12:29:20.593 回答
1

如果您查看pexpect.py源文件,您会发现记录日志的方法只是将发送/接收到子进程的内容写入流(可以是文件,例如,sys.stdout如果您更喜欢登录到控制台)。因此,如果不更改源,您所要求的是不可能的pexpect,例如,能够使用标准库日志记录模块 logger 进行输出(提示:也许是为项目做出改进的好机会?)。

于 2012-11-07T19:24:41.177 回答