Sure! There is no doubt some nonsense in here and things that I use to see what’s going on as this code progresses… but here is my beast.
[code]#Python.NET
from System.Collections.Specialized import *
from System.Drawing import *
from System.IO import *
from Deadline.Scripting import *
import os
import xlwt
from xlwt import Workbook, easyxf, Borders
from datetime import datetime
import shutil
scriptDialog = None
settings = None
def main():
global scriptDialog
global settings
job-pool selection window
scriptDialog = DeadlineScriptEngine.GetScriptDialog()
scriptDialog.SetSize( 400, 130 )
scriptDialog.SetTitle( "Job Selection" )
scriptDialog.SetIcon( Path.Combine( GetRootDirectory(), "scripts/General/RenderBilling/RenderBilling.ico" ) )
scriptDialog.AddRow()
scriptDialog.AddControl( "DefineTool", "LabelControl", "This tool will calculate the total render time for job billing.", 380, -1 )
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.AddControl( "PoolLabel", "LabelControl", "Select the job:", 100, -1 )
scriptDialog.AddControl( "PoolBox", "PoolComboControl", "job", 200, -1 )
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.AddControl( "DummyLabel1", "LabelControl", "", 205, -1 )
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.AddControl( "DummyLabel2", "LabelControl", "Once you hit Select, please be patient. A pop up will appear with your total.", 385, -1 )
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.AddControl( "DummyLabel3", "LabelControl", "", 175, -1 )
selectButton = scriptDialog.AddControl( "SelectButton", "ButtonControl", "Select", 100, -1 )
selectButton.ValueModified += SelectButtonPressed
closeButton = scriptDialog.AddControl( "CloseButton", "ButtonControl", "Close", 100, -1 )
closeButton.ValueModified += CloseButtonPressed
scriptDialog.EndRow()
scriptDialog.ShowDialog( False )
def SelectButtonPressed( *args ):
get job from selection box
job = scriptDialog.GetValue( "PoolBox" )
check to make sure a job was selected
if job == "none":
# pop up with error
scriptDialog.ShowMessageBox( " Please select a job, you can't calculate NONE. ", "Error Message")
else:
CalculateJob()
def CalculateJob( *args ):
global scriptDialog
CloseButtonPressed()
begin = datetime.now()
get job from selection box
job = scriptDialog.GetValue( "PoolBox" )
get list of job IDs for the pool that are completed, archived or not
filter = "jobPool="
filter += job
poolArgs = StringCollection()
poolArgs.Add("GetJobIdsFilterAnd")
poolArgs.Add( filter )
poolArgs.Add( "status=Completed" )
jobidlist = []
poollist = ClientUtils.ExecuteCommandAndGetOutput( poolArgs )
poollist = poollist.split()
if poollist == []:
NoHours(job)
else:
declaring some variables
tt = 0 # total job time tallied
jt = 0 # job time
write to file for diagnostics
inp=file(’//queue/DeadlineRepository/scripts/General/RenderBilling/output.txt’, ‘w’)
cmp = len(poollist) # number of jobs that are completed
jobname = []
jobtimelist = []
totaltimelist = []
plugname = []
username = []
cmpdate = []
get time for each job
for i in range(len(poollist)):
jobid = str(poollist[i])
jobArgs = StringCollection()
jobArgs.Add("GetJobTaskTotalTime")
jobArgs.Add( jobid )
jobtime = ClientUtils.ExecuteCommandAndGetOutput( jobArgs )
d = float(jobtime[20:22])
h = float(jobtime[24:26])
m = float(jobtime[28:30])
s = float(jobtime[32:34])
jt = (86400*d+3600*h+60*m+s)
jt /= 3600
tt += jt
add job time to list
jobtimelist.append(jt)
add total job time to list
totaltimelist.append(tt)
add job name to list
nameArgs = StringCollection()
nameArgs.Add("GetJobSetting")
nameArgs.Add(jobid)
nameArgs.Add("name")
jobname.append( ClientUtils.ExecuteCommandAndGetOutput( nameArgs ))
add plug-in to list
plugArgs = StringCollection()
plugArgs.Add("GetJobSetting")
plugArgs.Add(jobid)
plugArgs.Add("pluginname")
plugname.append( ClientUtils.ExecuteCommandAndGetOutput( plugArgs ))
add artist to list
userArgs = StringCollection()
userArgs.Add("GetJobSetting")
userArgs.Add(jobid)
userArgs.Add("username")
username.append( ClientUtils.ExecuteCommandAndGetOutput( userArgs ))
add completion date to list
dateArgs = StringCollection()
dateArgs.Add("GetJobSetting")
dateArgs.Add(jobid)
dateArgs.Add("completeddatetime")
cmpdate.append( ClientUtils.ExecuteCommandAndGetOutput( dateArgs ))
pop up if no hours exist
if tt == 0:
NoHours()
inp.write('job name = ’ + str(jobname[i]) + ‘\n’)
#################################################
#################################################
define excel doc and sheet
wb = xlwt.Workbook()
ws = wb.add_sheet('RenderStats')
style1 = xlwt.XFStyle()
style1.num_format_str = ‘D-MMM-YY’
font2 = xlwt.Font()
font2.colour_index = 1
style2 = xlwt.XFStyle()
style2.font = font2
define a style for a bottom border
borders = Borders()
borders.bottom = Borders.MEDIUM
styleB = xlwt.XFStyle()
styleB.borders = borders
avgrentime = round(tt/cmp,2)
datemin = min(cmpdate)[:10]
datemax = max(cmpdate)[:10]
ws.write(0, 1, job)
ws.write(1, 1, "Report date: " + str(datetime.now().strftime('%Y-%m-%d')) + " @ " + str(datetime.now().strftime('%H:%M')))
ws.write(2, 1, "Total render time: " + str(round(tt,2)) + " hours")
ws.write(3, 1, "Number of jobs submitted: " + str(cmp) + " jobs")
ws.write(4, 1, "Average render time: " + str(avgrentime) + " hours")
ws.write(5, 1, "Project dates: " + str(datemin) + " to " + str(datemax))
establish table headers
ws.write(7, 0, "#", styleB)
ws.write(7, 1, "ID", styleB)
ws.write(7, 2, "Name", styleB)
ws.write(7, 3, "Application", styleB)
ws.write(7, 4, "Artist", styleB)
ws.write(7, 5, "Date", styleB)
ws.write(7, 6, "Time", styleB)
ws.write(7, 7, "Deadline Tally", styleB)
ws.write(7, 8, "Excel Tally", styleB)
ws.write(7, 9, "Discrepancies?", styleB)
start for loop here
declare max length variables
maxId = 20
maxName = 8
maxApp = 8
maxArtist = 5
maxDate = 8
maxTime = 4
maxTallyDl = 10
maxTallyEx = 8
maxDscp = 10
for r in range(len(poollist)):
myRow = r + 8
myCell = r + 9
jobCounter = r+1
formula1 = "round(sum(L9:L" + str(myCell) + "),2)"
formula2 = "if(H" + str(myCell) + "-I" + str(myCell) + "=0,\"\",\"yes\")"
formulaJT = "round(L" + str(myCell) + ",2)"
formulaTT = "round(M" + str(myCell) + ",2)"
ws.write(myRow, 0, jobCounter)
ws.write(myRow, 1, poollist[r])
ws.write(myRow, 2, jobname[r])
ws.write(myRow, 3, plugname[r])
ws.write(myRow, 4, username[r])
ws.write(myRow, 5, cmpdate[r][:10])
ws.write(myRow, 6, xlwt.Formula(formulaJT))
ws.write(myRow, 7, xlwt.Formula(formulaTT))
ws.write(myRow, 11, jobtimelist[r], style2)
ws.write(myRow, 12, totaltimelist[r], style2)
ws.write(myRow, 8, xlwt.Formula(formula1))
discrepancy
ws.write(myRow, 9, xlwt.Formula(formula2))
find max lengths
if maxName < len(jobname[r]):
maxName = len(jobname[r])
if maxApp < len(plugname[r]):
maxApp = len(plugname[r])
if maxArtist < len(username[r]):
maxArtist = len(username[r])
if maxTime < len(str(round(jobtimelist[r],2))):
maxTime = len(str(round(jobtimelist[r],2)))
set column widths
ws.col(0).width = 1250
ws.col(1).width = (maxId+4)*256 # max letter length + 4
ws.col(2).width = (maxName+1)*256
ws.col(3).width = (maxApp+4)*256
ws.col(4).width = (maxArtist+4)*256
ws.col(5).width = (maxDate+4)*256
ws.col(6).width = (maxTime+4)*256
ws.col(7).width = (maxTallyDl+4)*256
ws.col(8).width = (maxTallyEx+4)*256
ws.col(9).width = (maxDscp+4)*256
save spreadsheet
location = '\\\\queue\\DeadlineRepository\\scripts\\General\\RenderBilling\\output\\' + job + '_' + str(datetime.now().strftime('%Y-%m-%d')) + '.xls'
wb.save(location)
##################################################
##################################################
inp.write(’\n\ncompleted jobs ’ + str(cmp))
inp.close()
how long did this process take
end = datetime.now()
runtime = end - begin
round total render time to 2 decimal points
ttr = str(round(tt,2))
results and email window
scriptDialog = DeadlineScriptEngine.GetScriptDialog()
scriptDialog.SetSize( 450, 200 )
scriptDialog.SetTitle( "Render Results" )
scriptDialog.SetIcon( Path.Combine( GetRootDirectory(), "scripts/General/RenderBilling/RenderBilling.ico" ) )
scriptDialog.AddRow()
scriptDialog.AddControl( "DTool2", "LabelControl", "Total "+ ttr + " hours for job " + filter[8:] + ". (" + str(cmp) + " completed jobs)", 380, -1)
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.AddControl( "DefineTool3", "LabelControl", "Choose an action below:", 380, -1)
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.AddControl( "ComboLabel", "LabelControl", "Select An Action", 120, -1 )
scriptDialog.AddComboControl( "CBox", "ComboControl", "Save and Email", ("Save and Email","Save only","Email only","Discard results"), 175, -1 )
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.AddControl( "EmailLabel", "LabelControl", "Enter email address here: ", 120, -1 )
scriptDialog.AddControl( "EmailAddress", "TextControl", "", 300, -1 )
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.AddControl( "SaveFolderLabel", "LabelControl", "Select folder:", 120, -1 )
scriptDialog.AddSelectionControl( "SaveFolder", "FolderBrowserControl", "", "", 300, -1 )
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.AddControl( "DummyLabel5", "LabelControl", "", 205, -1 )
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.AddControl( "DefineTool10", "LabelControl", "Script run time: " + str(runtime)[:7], 380, -1)
scriptDialog.EndRow()
scriptDialog.AddRow()
scriptDialog.AddControl( "DummyLabel6", "LabelControl", "", 225, -1 )
selectButton = scriptDialog.AddControl( "SendButton", "ButtonControl", "OK", 100, -1 )
selectButton.ValueModified += SendButtonPressed
closeButton = scriptDialog.AddControl( "CloseButton", "ButtonControl", "Discard", 100, -1 )
closeButton.ValueModified += CloseButtonPressed
scriptDialog.EndRow()
scriptDialog.ShowDialog( False )
def SendButtonPressed( location, *args ):
global scriptDialog
scriptDialog.CloseDialog()
action = scriptDialog.GetValue( “CBox” )
if action == “Save and Email”:
save = scriptDialog.GetValue( “SaveFolder” )
email = scriptDialog.GetValue( “EmailAddress” )
scriptDialog.ShowMessageBox( "Save to " + save + " and Email to " + email, “action01”)
if action == “Save only”:
save = scriptDialog.GetValue( “SaveFolder” )
shutil.copy2(location,“C:\moved.xls”)
if action == “Email only”:
email = scriptDialog.GetValue( “EmailAddress” )
scriptDialog.ShowMessageBox( "Email only to " + email, “action03”)
if action == “Discard results”:
scriptDialog.ShowMessageBox( “Discard results”, “action04”)
CloseButtonPressed()
def CloseButtonPressed( *args ):
global scriptDialog
scriptDialog.CloseDialog()
def NoHours( x ):
global scriptDialog
scriptDialog.CloseDialog()
job = scriptDialog.GetValue( “PoolBox” )
scriptDialog.ShowMessageBox( " There are no hours for job " + x + " ", "No Render Time")[/code]
if I had to paraphrase, this is what is going on.
[code]main():
popup window where you select the job you want to tally
ok or cancel buttons
SelectButtonPressed(*args):
makes sure you selected a job, if not it takes you back to main, if you did it send you to calculate
CalculateJob(*args):
makes tons of lists with all the data and also gets some running totals
makes the excel document
pops up a review dialog box with 4 options (save and email, save, email or discard) - all options lead to the next function which has if statements for the options
SendButtonPressed(*args):
if save and email, do that
if save, do that
if email, do that
if discard, delete the file
CloseButtonPressed(*arg):
closes dialog boxes and exits functions
NoHours(*args):
pop up returned if there are no rendered jobs for the project[/code]
I could use global variable… I was trying to avoid them only based on reading online over and over that they were bad or a cheap way out (I believe everything I read online when it comes to code since I don’t know any better!). This code works until you get to the last SendButtonPressed in the 2nd dialog box at the end CalculateJob function. If using global variable is an easy and suggested solution I’ll do that! I didn’t want to re-declare variables that I need to match, and accidentally have them mismatch and break stuff.
Let me give the global variables a try. Thanks!
brad
PS - if you look at my code and scratch your head, well, I’m learning as I go!