#!/usr/bin/env python3 """Write information into a logfile, like the timestamp and the hostname.""" import os import socket from datetime import date from datetime import datetime # Determine if the OS is MS Windows if os.name == 'nt': # Set the location of the file to write to, in the user Documents directory logfile = os.path.join(os.path.join(os.environ['USERPROFILE']), r'Documents\logoff.log') # For OS which are not MS Windows else: logfile = os.path.join(os.path.join(os.environ['HOME']), r'Documents/logoff.log') # Create the file if it does not exist yet if not os.path.exists(logfile): with open(logfile, 'w'): pass # Determine the current date and time today = date.today() now = datetime.now() current_day = today.strftime("%d.%m.%Y") current_time = now.strftime("%H:%M:%S") # Determine the client hostname client_hostname = os.getenv("CLIENTNAME") # Determine the client hostname via a different method # in case the first one failed if client_hostname is None: client_hostname = socket.gethostbyaddr(socket.gethostname())[0] # Class for prepending the date and time to the log file class Prepender(object): def __init__(self, file_path, ): # Read in the existing file, so we can write it back later with open(file_path, mode='r') as f: self.__write_queue = f.readlines() self.__open_file = open(file_path, mode='w') def write_line(self, line): self.__write_queue.insert(0, "%s\n" % line, ) def write_lines(self, lines): lines.reverse() for line in lines: self.write_line(line) def close(self): self.__exit__(None, None, None) def __enter__(self): return self def __exit__(self, type, value, traceback): if self.__write_queue: self.__open_file.writelines(self.__write_queue) self.__open_file.close() # Prepend the determined information to the top of the log file with Prepender(logfile) as f: # Must write individual lines in reverse order f.write_line(current_day+' - '+current_time+' - '+client_hostname) # Or, use write_lines instead - that maintains order. # with Prepender(logfile) as f: # f.write_lines( # ['This will be line 1', # 'This will be line 2', # 'This will be line 3', # ] # )