python at work (piemērs)
skalpelis
vaicāja, "Kā Pythonam ir ar pielietojuma iespējām?"
Sekojošās programmas
login.py
un
logout.py
nosūta e-pastu, kā arī palaiž ekseļa makrosu, kas izdara ierakstus xls failā. Rezultātā tiek ietaupīts mans un manu kolēģu dārgais darbalaiks un mēs varam doties dārzā pievilkties.
Tika izmantots Python 2.2.3, win32all, kā arī VBAXL9.CHM.
Iespējams COM kodu labāk taisīt iekš VB un tad pārvērst pitonā. Šī bija pirmā reize, kad to darīju.
Visi faili ir ļoti atkarīgi no config.py.
Daudzās vietās netiek pārbaudīts vai ārējās darbības sekmējās.
Lietotāji ir programmētāji.
login.py
from config import *
logmail.logIn()
excel.startTask()
logout.py
from config import *
logmail.logOut()
excel.endTask()
config.py
import logmail
import excel
excel.fileName = "C:\\sample.xls"
logmail.fromAddress = "my@adress.is"
logmail.toAddress = "log@mail.adress.com"
# logmail.toAddress = "@other mail"
logmail.mailBody = " "
logmail.mailserver = "mail.latnet.lv"
excel.py
from win32com.client import Dispatch
from pythoncom import CoInitialize, CoUninitialize
#shamo vajadzeetu ieksh try ..finally:
#karoche netiek kjertas kljuudas un apstraadaati iznjeemuma gadiijumi
def runMacroInLastSheet(fileName, macroName):
CoInitialize() # Initialize the COM libraries for the calling thread.
excel = Dispatch("Excel.Application")
excel.Visible = 0
excel.Workbooks.Open(Filename=fileName)
sheets = excel.Workbooks(1).Sheets
lastSheet = sheets(sheets.Count)
macro = lastSheet.CodeName + "." + macroName
excel.Run(macro)
excel.Workbooks(1).Save()
excel.Workbooks(1).Close(SaveChanges='0')
excel.Quit()
CoUninitialize()
def startTask():
runMacroInLastSheet(fileName, "AddNewStart_Click")
def endTask():
runMacroInLastSheet(fileName, "EndLastTask_Click")
logmail.py
"""
Sends short e-mail,
which contains current time in subject line, and short message in body.
Not useful without mailserver, fromAddress, toAddress and mailBody defined. (as strings)
"""
import smtplib
import time
def header(name, contents):
"""Formats message header."""
return name + ": " + contents + "\r\n"
def sendLogMail(mailserver, fromAddress, toAddress, mailBody, subject):
"""Sends email. Subject is used in subject line."""
currentTime = time.strftime("%Y.%m.%d. %H:%M")
msg = ""
msg = msg + header("From", fromAddress)
msg = msg + header("To", toAddress)
msg = msg + header("Subject", subject + " " + currentTime)
msg = msg + "\r\n"
msg = msg + mailBody
server = smtplib.SMTP(mailserver)
server.sendmail(fromAddress, toAddress, msg)
server.quit()
def logIn():
sendLogMail(mailserver, fromAddress, toAddress, mailBody, "Log in")
def logOut():
sendLogMail(mailserver, fromAddress, toAddress, mailBody, "Log out")