Я столкнулся с проблемой при создании PPT-файла автоматически, когда пользователь не вошел в систему с помощью планировщика задач. Я написал код на python, который создаст файл PPT и, в свою очередь, отправит его назначенным получателям. Код успешно выполнялся при планировании в планировщике заданий в запланированное время, когда я включил флажок «Пользователь вошел в систему», но не работал, когда я выбрал параметр флажка «Пользователь не вошел в систему».
Не могли бы вы предложить метод для успешного выполнения кода в планировщике задач, когда пользователь не вошел в систему.
import pyodbc
import pandas as pd
from openpyxl import load_workbook
from pptx import Presentation
import numpy as np
from datetime import datetime, timedelta
import smtplib
import win32com.client
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
os.chdir(r'C:\Personal\jthomas1\Documents\CASAutomation\PerformanceReportJojiVersion')
try:
def calculateValue(ws,position,ref_date,colname,range1,range2,df):
dt = pd.Series(datetime.combine(ref_date, datetime.min.time()))
dfEval = df[df['Week_Number'] == dt.dt.week[0]]
if len(dfEval.index)>0:
ws[position[0]] = round((len((dfEval[(dfEval[colname]<range1)]).index)/len(dfEval.index))*100) # For less than 5 seconds
ws[position[1]] = round((len((dfEval[(dfEval[colname]>=range1) & (dfEval[colname]<=range2)]).index)/len(dfEval.index))*100)
ws[position[2]] = round((len((dfEval[(dfEval[colname]>range2)]).index)/len(dfEval.index))*100)
ws[position[3]] = len(dfEval.index)
x = dfEval[colname].to_numpy()
ws[position[4]] = np.percentile(x,90,axis=None)
else:
ws[position[0]] = 0
ws[position[1]] = 0
ws[position[2]] = 0
ws[position[3]] = 0
ws[position[4]] = 0
#connect to db
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=server;DATABASE=DataBase;UID=uid;PWD=Pwd')
path = r'C:\Personal\jthomas1\Documents\CASAutomation\PerformanceReportJojiVersion\PerformanceReportMetricss.xlsx'
wb = load_workbook(path)
ws1 = wb.active
#Get CW-1 and update C1
lastDayofCWMinusone = datetime.now().date()-timedelta(days=5)
startofCWMinusone = lastDayofCWMinusone - timedelta(days=((lastDayofCWMinusone.weekday()+1)%7))
endofCWMinusone = startofCWMinusone +timedelta(days=6)
LWDateRange = startofCWMinusone.strftime('%m/%d/%Y') + '-' + endofCWMinusone.strftime('%m/%d/%Y')
ws1['C1'] = LWDateRange
#Get CW-2 and update G1
startofCWMinustwo = startofCWMinusone - timedelta(days=7)
endofCWMinustwo = endofCWMinusone - timedelta(days=7)
LWMinustwoRange = startofCWMinustwo.strftime('%m/%d/%Y') + '-' + endofCWMinustwo.strftime('%m/%d/%Y')
ws1['H1'] = LWMinustwoRange
#Get CW-3 and update K1
startofCWMinusthree = startofCWMinustwo - timedelta(days=7)
endofCWMinusthree = endofCWMinustwo - timedelta(days=7)
LWMinusthreeRange = startofCWMinusthree.strftime('%m/%d/%Y') + '-' + endofCWMinusthree.strftime('%m/%d/%Y')
ws1['M1'] = LWMinusthreeRange
#Get CW-4 and update O1
startofCWMinusfour = startofCWMinusthree - timedelta(days=7)
endofCWMinusfour = endofCWMinusthree - timedelta(days=7)
LWMinusfourRange = startofCWMinusfour.strftime('%m/%d/%Y') + '-' + endofCWMinusfour.strftime('%m/%d/%Y')
ws1['R1'] = LWMinusfourRange
#System Promo Calc
sSQL = "select * from promocalc where businessmodified>='{} 00:00:00' and businessmodified<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
promocalc = pd.read_sql(sSQL,conn,index_col=None)
promocalc['Week_Number'] = promocalc['businessmodified'].dt.week
calculateValue(ws1,['C3','D3','E3','F3','G3'],endofCWMinusone,"calctime (in Seconds)",5,10,promocalc)
calculateValue(ws1,['H3','I3','J3','K3','L3'],endofCWMinustwo,"calctime (in Seconds)",5,10,promocalc)
calculateValue(ws1,['M3','N3','O3','P3','Q3'],endofCWMinusthree,"calctime (in Seconds)",5,10,promocalc)
calculateValue(ws1,['R3','S3','T3','U3','V3'],endofCWMinusfour,"calctime (in Seconds)",5,10,promocalc)
#System Promo Overview
sSQL = "select * from ltapromooverview where (module='Promotion Overview using template profile' or module='PRM - SEARCH-PROFILE-TEMPLATE') and logdate>='{} 00:00:00' and logdate<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
promoOverview = pd.read_sql(sSQL,conn,index_col=None)
promoOverview['Week_Number'] = promoOverview['LOGDATE'].dt.week
calculateValue(ws1,['C4','D4','E4','F4','G4'],endofCWMinusone,"TIMETAKEN",5,10,promoOverview)
calculateValue(ws1,['H4','I4','J4','K4','L4'],endofCWMinustwo,"TIMETAKEN",5,10,promoOverview)
calculateValue(ws1,['M4','N4','O4','P4','Q4'],endofCWMinusthree,"TIMETAKEN",5,10,promoOverview)
calculateValue(ws1,['R4','S4','T4','U4','V4'],endofCWMinusfour,"TIMETAKEN",5,10,promoOverview)
#System Promo Save- Planned
sSQL = "select * from plannedunplannedpromo where orglevel='PLANNED' and logdate>='{} 00:00:00' and logdate<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
promoplannedSave = pd.read_sql(sSQL,conn,index_col=None)
promoplannedSave['Week_Number'] = promoplannedSave['LOGDATE'].dt.week
calculateValue(ws1,['C5','D5','E5','F5','G5'],endofCWMinusone,"TIMETAKEN",5,10,promoplannedSave)
calculateValue(ws1,['H5','I5','J5','K5','L5'],endofCWMinustwo,"TIMETAKEN",5,10,promoplannedSave)
calculateValue(ws1,['M5','N5','O5','P5','Q5'],endofCWMinusthree,"TIMETAKEN",5,10,promoplannedSave)
calculateValue(ws1,['R5','S5','T5','U5','V5'],endofCWMinusfour,"TIMETAKEN",5,10,promoplannedSave)
#System Transactions- Open P&L
sSQL = "select * from systemtransactions where (module='BPL - OPEN-TAB-P-AND-L_BplSegmentPrdSummaryDataView' or module='BPL - OPEN-TAB-P-AND-L_BplSegmentPrdSummaryPrdView' or module='BPL - OPEN-TAB-P-AND-L_BplDataHeaderView') and logdate>='{} 00:00:00' and logdate<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
openPandL = pd.read_sql(sSQL,conn,index_col=None)
openPandL['Week_Number'] = openPandL['LOGDATE'].dt.week
calculateValue(ws1,['C6','D6','E6','F6','G6'],endofCWMinusone,"TIMETAKEN",5,10,openPandL)
calculateValue(ws1,['H6','I6','J6','K6','L6'],endofCWMinustwo,"TIMETAKEN",5,10,openPandL)
calculateValue(ws1,['M6','N6','O6','P6','Q6'],endofCWMinusthree,"TIMETAKEN",5,10,openPandL)
calculateValue(ws1,['R6','S6','T6','U6','V6'],endofCWMinusfour,"TIMETAKEN",5,10,openPandL)
#system transaction-Payment Save
sSQL = "select * from systemtransactions where module='Payment Save' and logdate>='{} 00:00:00' and logdate<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
paymentsave = pd.read_sql(sSQL,conn,index_col=None)
paymentsave['Week_Number'] = paymentsave['LOGDATE'].dt.week
calculateValue(ws1,['C7','D7','E7','F7','G7'],endofCWMinusone,"TIMETAKEN",5,10,paymentsave)
calculateValue(ws1,['H7','I7','J7','K7','L7'],endofCWMinustwo,"TIMETAKEN",5,10,paymentsave)
calculateValue(ws1,['M7','N7','O7','P7','Q7'],endofCWMinusthree,"TIMETAKEN",5,10,paymentsave)
calculateValue(ws1,['R7','S7','T7','U7','V7'],endofCWMinusfour,"TIMETAKEN",5,10,paymentsave)
#System Transactions-Promo Delete
sSQL = "select * from systemtransactions where module='Promotion Delete' and logdate>='{} 00:00:00' and logdate<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
promodelete = pd.read_sql(sSQL,conn,index_col=None)
promodelete['Week_Number'] = promodelete['LOGDATE'].dt.week
calculateValue(ws1,['C8','D8','E8','F8','G8'],endofCWMinusone,"TIMETAKEN",5,10,promodelete)
calculateValue(ws1,['H8','I8','J8','K8','L8'],endofCWMinustwo,"TIMETAKEN",5,10,promodelete)
calculateValue(ws1,['M8','N8','O8','P8','Q8'],endofCWMinusthree,"TIMETAKEN",5,10,promodelete)
calculateValue(ws1,['R8','S8','T8','U8','V8'],endofCWMinusfour,"TIMETAKEN",5,10,promodelete)
#System Transactions-Promo Copy
sSQL = "select * from systemtransactions where module='Promotion Copy' and logdate>='{} 00:00:00' and logdate<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
promocopy = pd.read_sql(sSQL,conn,index_col=None)
promocopy['Week_Number'] = promocopy['LOGDATE'].dt.week
calculateValue(ws1,['C9','D9','E9','F9','G9'],endofCWMinusone,"TIMETAKEN",5,10,promocopy)
calculateValue(ws1,['H9','I9','J9','K9','L9'],endofCWMinustwo,"TIMETAKEN",5,10,promocopy)
calculateValue(ws1,['M9','N9','O9','P9','Q9'],endofCWMinusthree,"TIMETAKEN",5,10,promocopy)
calculateValue(ws1,['R9','S9','T9','U9','V9'],endofCWMinusfour,"TIMETAKEN",5,10,promocopy)
#System workflow- Planning to Evaluate
sSQL = "select * from workflow where code='PlanningToEvaluate' and intime>='{} 00:00:00' and intime<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
planningtoEvaluate = pd.read_sql(sSQL,conn,index_col=None)
planningtoEvaluate['Week_Number'] = planningtoEvaluate['intime'].dt.week
calculateValue(ws1,['C12','D12','E12','F12','G12'],endofCWMinusone,"timetaken (Seconds)",15,20,planningtoEvaluate)
calculateValue(ws1,['H12','I12','J12','K12','L12'],endofCWMinustwo,"timetaken (Seconds)",15,20,planningtoEvaluate)
calculateValue(ws1,['M12','N12','O12','P12','Q12'],endofCWMinusthree,"timetaken (Seconds)",15,20,planningtoEvaluate)
calculateValue(ws1,['R12','S12','T12','U12','V12'],endofCWMinusfour,"timetaken (Seconds)",15,20,planningtoEvaluate)
#System workflow- Planning to Submit
sSQL = "select * from workflow where code='PlanningToSubmit' and intime>='{} 00:00:00' and intime<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
planningtoSubmit = pd.read_sql(sSQL,conn,index_col=None)
planningtoSubmit['Week_Number'] = planningtoSubmit['intime'].dt.week
calculateValue(ws1,['C13','D13','E13','F13','G13'],endofCWMinusone,"timetaken (Seconds)",15,20,planningtoSubmit)
calculateValue(ws1,['H13','I13','J13','K13','L13'],endofCWMinustwo,"timetaken (Seconds)",15,20,planningtoSubmit)
calculateValue(ws1,['M13','N13','O13','P13','Q13'],endofCWMinusthree,"timetaken (Seconds)",15,20,planningtoSubmit)
calculateValue(ws1,['R13','S13','T13','U13','V13'],endofCWMinusfour,"timetaken (Seconds)",15,20,planningtoSubmit)
#System Promo Save- UnPlanned
sSQL = "select * from plannedunplannedpromo where orglevel='UNPLANNED' and logdate>='{} 00:00:00' and logdate<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
promounplannedSave = pd.read_sql(sSQL,conn,index_col=None)
promounplannedSave['Week_Number'] = promounplannedSave['LOGDATE'].dt.week
calculateValue(ws1,['C14','D14','E14','F14','G14'],endofCWMinusone,"TIMETAKEN",15,20,promounplannedSave)
calculateValue(ws1,['H14','I14','J14','K14','L14'],endofCWMinustwo,"TIMETAKEN",15,20,promounplannedSave)
calculateValue(ws1,['M14','N14','O14','P14','Q14'],endofCWMinusthree,"TIMETAKEN",15,20,promounplannedSave)
calculateValue(ws1,['R14','S14','T14','U14','V14'],endofCWMinusfour,"TIMETAKEN",15,20,promounplannedSave)
#System LTA Overview
sSQL = "select * from ltapromooverview where (module='LTA Overview using identification profile' or module='LTA - SEARCH-PROFILE-IDENTIFICATION') and logdate>='{} 00:00:00' and logdate<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
ltaProfile = pd.read_sql(sSQL,conn,index_col=None)
ltaProfile['Week_Number'] = ltaProfile['LOGDATE'].dt.week
calculateValue(ws1,['C17','D17','E17','F17','G17'],endofCWMinusone,"TIMETAKEN",20,25,ltaProfile)
calculateValue(ws1,['H17','I17','J17','K17','L17'],endofCWMinustwo,"TIMETAKEN",20,25,ltaProfile)
calculateValue(ws1,['M17','N17','O17','P17','Q17'],endofCWMinusthree,"TIMETAKEN",20,25,ltaProfile)
calculateValue(ws1,['R17','S17','T17','U17','V17'],endofCWMinusfour,"TIMETAKEN",20,25,ltaProfile)
#System Business Segment Update
sSQL = "select * from updatesegment where businessmodified>='{} 00:00:00' and businessmodified<='{} 23:59:59'".format(startofCWMinusfour.strftime('%m-%d-%Y'),endofCWMinusone.strftime('%m-%d-%Y'))
updatesegment = pd.read_sql(sSQL,conn,index_col=None)
updatesegment['Week_Number'] = updatesegment['BUSINESSMODIFIED'].dt.week
calculateValue(ws1,['C20','D20','E20','F20','G20'],endofCWMinusone,"Calc time (in Minutes)",3,5,updatesegment)
calculateValue(ws1,['H20','I20','J20','K20','L20'],endofCWMinustwo,"Calc time (in Minutes)",3,5,updatesegment)
calculateValue(ws1,['M20','N20','O20','P20','Q20'],endofCWMinusthree,"Calc time (in Minutes)",3,5,updatesegment)
calculateValue(ws1,['R20','S20','T20','U20','V20'],endofCWMinusfour,"Calc time (in Minutes)",3,5,updatesegment)
wb.save(r'C:\Personal\jthomas1\Documents\CASAutomation\PerformanceReportJojiVersion\PerformanceReportMetrics.xlsx')
wb.close()
# Reading Excel and transferring to PPT
f = open(r'C:\Personal\jthomas1\Documents\CASAutomation\PerformanceReportJojiVersion\Performance Reports.pptx','rb')
prs = Presentation(f)
prs.slide_width =12900000
prs.slide_height =6686550
prs.save("Performance Reports.pptx")
f.close()
ExcelApp = win32com.client.Dispatch("Excel.Application")
ExcelApp.Visible = False
workbook = ExcelApp.Workbooks.open(r'C:\Personal\jthomas1\Documents\CASAutomation\PerformanceReportJojiVersion\PerformanceReportMetrics.xlsx')
worksheet = workbook.Worksheets("Summary")
excelrange = worksheet.Range("A1:V20")
PptApp = win32com.client.Dispatch("Powerpoint.Application")
z = excelrange.Copy()
pathx=r'C:\Personal\jthomas1\Documents\CASAutomation\PerformanceReportJojiVersion\Performance Reports.pptx'
PPtPresentation = PptApp.Presentations.Open(pathx,WithWindow=False)
pptSlide = PPtPresentation.Slides.Add(1,11)
title = pptSlide.Shapes.Title
title.TextFrame.TextRange.Text = 'Metrics Summary'
pptSlide.Shapes.Paste(z)
PPtPresentation.SaveAs(r'C:\Personal\jthomas1\Documents\CASAutomation\PerformanceReportJojiVersion\Performance Report.pptx',11)
workbook.Save()
workbook.Close(True)
# Sending Mail using SMTP
filepath = r'C:\Personal\jthomas1\Documents\CASAutomation\PerformanceReport\Performance Reports.pptx'
filepath1 = r'C:\Personal\jthomas1\Documents\CASAutomation\PerformanceReportJojiVersion\PerformanceReportMetrics.xlsx'
fromEmail = 'abc@xyz.com'
toEmail = ['abc@abc.com','mrx@aol.com']
toEmail1 =['abc@aol.com','mrx@abc.com']
subject = 'Performance Report Metrics - Test Mail'
subject1 = 'Performance Metrics Excel file Updated'
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = fromEmail
msg['To'] = ", ".join(toEmail)
msg1 = MIMEMultipart('alternative')
msg1['Subject'] = subject1
msg1['From'] = fromEmail
msg1['To'] = ",".join(toEmail1)
# msg1['Cc'] = ",".join(ccEmail1)
body = ''' Hi All,
Please find the performance report attached in this email.
Thanks and Regards,
Matt '''
body1 = ''' Hi All,
Please find the updated excel metrics file attached in this email.
Thanks and Regards,
Matt '''
msg.attach(MIMEText(body,'plain'))
msg1.attach(MIMEText(body1, 'plain'))
if os.path.exists(filepath):
attachment = open(filepath, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
filename ='Performance Report.pptx'
part.add_header('Content-Disposition',
"attachment; filename= %s" % filename)
msg.attach(part)
attachment.close()
s = smtplib.SMTP('mail:25')
s.sendmail(fromEmail, toEmail, msg.as_string())
s.quit()
if os.path.exists(filepath1):
attachment1 = open(filepath1, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment1).read())
encoders.encode_base64(part)
filename1 = 'PerformanceReportMetrics.xlsx'
part.add_header('Content-Disposition',
"attachment; filename= %s" % filename1)
msg1.attach(part)
attachment1.close()
s1 = smtplib.SMTP('mail:25')
s1.sendmail(fromEmail, toEmail1, msg1.as_string())
s1.quit()
except Exception as e:
f=open('log.txt','w')
f.write('An Exception occured-%s' %e)
f.close()