I'm just starting on Python and maybe I'm worrying too much too soon, but anyways...
log = "/tmp/trefnoc.log"
def logThis (text, display=""):
msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text
if display != None:
print msg + display
logfile = open(log, "a")
logfile.write(msg + "\n")
logfile.close()
return msg
def logThisAndExit (text, display=""):
msg = logThis(text, display=None)
sys.exit(msg + display)
That is working, but I don't like how it looks. Is there a better way to write this (maybe with just 1 function) and is there any other thing I should be concerned under exiting?
Now to some background...
Sometimes I will call logThis just to log and display. Other times I want to call it and exit. Initially I was doing this:
logThis ("ERROR. EXITING")
sys.exit()
Then I figured that wouldn't properly set the stderr, thus the current code shown on the top.
My first idea was actually passing "sys.exit" as an argument, and defining just logThis ("ERROR. EXITING", call=sys.exit) defined as following (showing just the relevant differenced part):
def logThis (text, display="", call=print):
msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text
call msg + display
But that obviously didn't work. I think Python doesn't store functions inside variables. I couldn't (quickly) find anywhere if Python can have variables taking functions or not! Maybe using an eval function? I really always try to avoid them, tho. Sure I thought of using if instead of another def, but that wouldn't be any better or worst.
Anyway, any thoughts?