Debugging a Python Scheduled Task
I have been working on a python script that I want (NEED) to run as a scheduled task on a remote machine. I got to the point that the script did exactly what I needed when I was interactively running it in a Windows session but had problems when running it as a scheduled task. The debugging process was cumbersome–make a change, schedule a task to run it, log out of the machine, and wait. The log back in and repeat the process.
That got old.
So I wrote a script (tester.py) that calls any other python scripts in the same directory that (1) start with ‘test_’ and (2) there is not a corresponding file with the same base name and ‘.start’ extension. It would launch ‘test_BaBing.py’ as long as there is not a ‘test_BaBing.start’ in the same directory. Tester.py continued to run, looping every 60 seconds, until tester.stop exists.
This made the process easier because I could work on my local machine, editing the problematic script, saving changes and within 60 seconds it would be launched on the remote machine. I could view the results, make additional edits, delete the .start file and it would launch again within 60 seconds.
Within a couple minutes I was able to determine the problem (path related) and fix it.
Happy programmer.
Download: tester.py
import sys, string, os
import glob
import datetime, shutil
import time, inspect
import getpass
totalstarttime = datetime.datetime.now()
dateString = datetime.date.today().strftime("%Y%m%d_")+datetime.datetime.now().strftime("%H%M%S") #datetime.date.today().strftime("%Y%m%d")
debugfile = inspect.getfile(inspect.currentframe()).replace(".py","_"+dateString+"_Debug.txt")
stopfile = inspect.getfile(inspect.currentframe()).replace(".py",".stop")
newdebugfile = False
codeDir = os.path.dirname(inspect.getfile(inspect.currentframe())).replace("\","/")
def printit(inText):
global newdebugfile
print inText
if os.path.exists(debugfile):
if (newdebugfile == False):
tmpfile = open(debugfile,"w")
newdebugfile = True
else:
tmpfile = open(debugfile,"a")
else:
tmpfile = open(debugfile,"w")
tmpfile.write(inText)
tmpfile.write("n")
tmpfile.close()
newdebugfile = True
stopFileExists = False
printit("Code Directory: "+codeDir)
printit("Starting at: "+datetime.date.today().strftime("%Y-%m-%d_")+datetime.datetime.now().strftime("%H:%M:%S"))
printit("Stopfile : "+stopfile+"/n")
while (stopFileExists == False):
for iFile in glob.glob(codeDir+"/test_*.py"):
thisStartfile = iFile.replace(".py",".start")
if not (os.path.exists(thisStartfile)):
printit ("Launching: "+iFile)
iTmpfile = open(thisStartfile,"w")
iTmpfile.write("started")
iTmpfile.close()
os.system("Start "+iFile)
if (os.path.exists(stopfile)):
stopFileExists = True
else:
time.sleep(60)
printit("nEnd of Loop: "+datetime.date.today().strftime("%Y-%m-%d_")+datetime.datetime.now().strftime("%H:%M:%S")+"n")
printit("Done!")