我正在使用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')))
关于python - 如何在pexpect的日志文件中获取时间戳,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13271686/