Difference between revisions of "Python:Template"

From wiki
Jump to navigation Jump to search
Line 29: Line 29:
 
timestamp = datetime.now().strftime("%y%m%d_%H%M%S")
 
timestamp = datetime.now().strftime("%y%m%d_%H%M%S")
  
 +
logfile2name = logfile2name.replace('timestamp',timestamp)
 +
logfile,logfilename = openlog()
 +
logfile2 = openlog(<apath>)[0]                                    # Get only filehandler, not the file name
  
 
def main():
 
def main():
    logfile2name = logfile2name.replace('timestamp',timestamp)
 
    logfile,logfilename = openlog()
 
    logfile2 = openlog(<apath>)[0]                                  # If you don't care about the logfilename
 
 
     writelog(logfile,"This is in the logfile with generated name")
 
     writelog(logfile,"This is in the logfile with generated name")
 
     writelog(logfile2,"This is in the logfile with specified name")
 
     writelog(logfile2,"This is in the logfile with specified name")

Revision as of 14:40, 19 October 2018

Template for Python programs. Creating logfiles, standard modules to load, opening files, user configuration.

Code for mailing is on this wiki too.

ToDO:

  • Parsing commandline options
def usage():
    print ("Usage: "+__file__)
    print("Template for python programs")
    version = 'R1A, 20181010, Initial release'
    print("Version: "+version)
    sys.exit(1)


# USER CONFIGURABLE ITEMS

warning = 'If you need to modify these variables anywhere else you have to declare it global there'
filespec =  '*.*'
logfile2name = '<apath>_timestamp.txt'

# END USER CONFIGURABLE ITEMS, DO NOT CHANGE ANYTHING BELOW THIS LINE

import os,sys,re,glob
from datetime import datetime
timestamp = datetime.now().strftime("%y%m%d_%H%M%S")

logfile2name = logfile2name.replace('timestamp',timestamp)
logfile,logfilename = openlog()
logfile2 = openlog(<apath>)[0]                                     # Get only filehandler, not the file name

def main():
    writelog(logfile,"This is in the logfile with generated name")
    writelog(logfile2,"This is in the logfile with specified name")
    openfile(filespec)

    return

def openfile(filespec):
    filelist = glob.glob(filespec)
    for filename in filelist:
        if os.path.isfile(filename):
            with open (filename,"r") as file:
                for line in file:
                    <codeblock>
    return


def writelog (logfile,message):
    try:
        logfile.name
    except AttributeError:
        print("ERROR: Logfile is not open")
        usage()
    else:
        logfile.write(datetime.now().strftime("%y%m%d_%H%M%S_%f")+" "+message+"\n")
    return


def openlog (logfilename = ''):
    if logfilename == '':
        logfilename = __file__.replace('/bin/','/log/')
        logfilename += '_'+datetime.now().strftime("%y%m%d_%H%M")+'.log'
    try:
        logfile.name
    except UnboundLocalError:
        logfile = open (logfilename,"a")
    return(logfile,logfilename)

main()