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 (but not about trefnoc)…
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?
There’s no reason for “logThisAndExit”, it doesn’t save you much typing over
(compare
logThisAndExit(text, display))or
(compare
logThisAndExit(text))Not that I’m entirely sure why you like your exit messages formatted as log lines.
In answer to your original question: you’re missing parentheses:
call(msg+display)works fine. But I think that’s waaaay overengineering for logging/exiting stuff. Anyone who maintains your code will have to understand your function to know when it’s exiting and when it’s not.