I am using pexpect to handle my telnet and ssh communication.
I am also writing all request/response in a logfile. using pexpect.logfile(filename).
I would like to have timestamps in the logfile as well. I can not find it anywhere in the documentation! Does anyone have any idea how to implement this functionality?
logfile can be any object that has write(), flush() methods:
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 could be simplified:
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')))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With