I have a function (usually in a utils.py file with others) called myMsgs so it will print whether using and external IDE, the python window or want it to write to the Results window. It may double the print if in the Desktop python window, but I can live with that. I actually have several handy functions (message with or without logging, and with out without time stamping....a "sleep" for scripts that get ahead of themselves and need to be paused, etc). I'll just post the entite file so you can tweak or use other parts.
import time
import arcpy
import os
from time import localtime
def mySleep(secs):
myMsgs(" zzz...sleeping {0} seconds to allow network file status to catch up....".format(secs))
time.sleep(secs)
def timeStamp():
return time.strftime(' - %B %d - %H:%M:%S')
def myMsgsNoLog(message):
arcpy.AddMessage(message)
print(message)
def myMsgs(message):
arcpy.AddMessage("{0} {1}".format(message, curTime()))
print("{0} {1}".format(message, curTime()))
global messageCount
logFolder = r"C:\ESRITEST"
if not arcpy.Exists(logFolder):
arcpy.CreateFolder_management(os.sep.join(logFolder.split(os.sep)[:-1]), logFolder.split(os.sep)[-1])
mdy = curDate()
logName = "logfile_" + "_".join(mdy.split("/")) + ".log"
logFile = open(os.path.join(logFolder, logName), "a")
if message.lower() == "blank line":
logFile.write("\n\n")
print('\n\n')
elif message.lower() == "close logfile":
logFile.write("\n\n***** finished *****\n\n")
logFile.close()
else:
messageCount += 1
logFile.write("0" * (5 - len(str(messageCount))) + str(messageCount) + ". ")
logFile.write(message)
logFile.write("\n")
def curDate():
rawTime = localtime()
yr = str(rawTime[0])
mo = str(rawTime[1]).zfill(2)
dy = str(rawTime[2]).zfill(2)
return "/".join([mo, dy, yr])
def curTime():
rawTime = localtime()
hr = str(rawTime[3]).zfill(2)
mins = str(rawTime[4]).zfill(2)
secs = str(rawTime[5]).zfill(2)
return (":".join([hr, mins, secs]))
def curFileDateTime():
rawTime = localtime()
yr = str(rawTime[0])
mo = str(rawTime[1]).zfill(2)
dy = str(rawTime[2]).zfill(2)
hr = str(rawTime[3]).zfill(2)
mn = str(rawTime[4]).zfill(2)
return (yr + mo + dy + "_" + hr + mn)
def archiveDate():
rawTime = localtime()
yr = str(rawTime[0])
mo = str(rawTime[1]).zfill(2)
dy = str(rawTime[2]).zfill(2)
hr = str(rawTime[3]).zfill(2)
mn = str(rawTime[4]).zfill(2)
return "".join([yr, mo, dy, hr, mn])
def jdayShort():
import time
from time import localtime
return localtime()[7]
messageCount = 0