Skip to main content
 首页 » 编程设计

python之如何在 pexpect 的日志文件中获取时间戳

2025年05月04日17bluestorm

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

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

请您参考如下方法:

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