Advice on this code

L

LenS

If this is the wrong place to post this, please advise better place.
Otherwise, I have created the following python program and it works.
Running on XP. I think I am now at that stage of learning python where
I'm not quit a newbie and I am not really knowlegable. I know just
enough to be dangerous and can really screw things up.

Any suggestion on improving would be greatly appreciated. However my
real question is I would like to run this program under a GUI interface
and have the GUI have a start button to start this process running and
the messages in the program placed in a multiline text field which when
the stop button is pressed the text field would be copied to a logfile
and the program exited. Below this program is the skeleton of the
python gui program using wxPython (the gui program also works). I have
a metal block on merging the two programs. I think part of the problem
is the first is not really using object except for the database access
and the gui is all object. Second, I'am getting all wrapped up with
variable, object, etc scope issues.



** FIRST PROGRAM **
"""This program is an attempt to modularize the lmsface program.
I also will try to document the logic of the program"""

import os
import glob
import time
import re
import shutil

from win32com.client import Dispatch
from ADOConstants import *

def cvtfiles():
""" cvtfiles is the driving routine for converting and/or changing
the V1sta quote flat file being sent by QuotePro to Unique. The
function gets a list of the files in the FTP directory path and
opens each file one at a time and copies the data (with any
necessary changes or additions to the output directory where
V1sta's
interface program
picks it up and converts it into the V1sta's
SQL quote files. Individual functions are called to process
different segments of the flat file record."""

global novehflag
novehflag = False
global ofile
list1 = glob.glob('*.dat')
for f1 in list1:
if f1.lower().startswith("unq"):
if f1.lower().rfind("void") < 0:
print f1 + " is being processed now."
input1 = open(cfdir + f1, 'r')
output = open(ctdir + f1, 'w+')
ifile = input1.readline()
output.write(wrkpol(ifile))
output.write(wrkdrv(ifile,1406,6))
output.write(wrkveh(ifile,1784,6))
if novehflag == True:
input1.close()
output.close()
shutil.copy2(cfdir + f1,cfdir + 'voided\\' + f1)
os.remove(cfdir + f1)
os.remove(ctdir + f1)
novehflag = False
else:
output.write(wrkmisc(ifile,2582))
output.write(wrkviol(ifile,2774,16))
output.write(wrkaccid(ifile,3270,16))
output.write(wrkmisc2(ifile,3638))
output.write(wrkcov(ifile,3666,6))
output.write(wrklp(ifile,4314,7))
output.write(wrkai(ifile,4909,6))
output.write(wrkmisc3(ifile,5707))
output.close()
input1.close()
shutil.copy2(cfdir + f1,cfdir + 'processed\\' + f1)
os.remove(cfdir + f1)
print f1 + " has been processed."
else:
shutil.copy2(cfdir + f1,cfdir + 'voided\\' + f1)
os.remove(cfdir + f1)
print f1 + " is a VOIDED Quote from QuotePro."
else:
pass


def wrkpol(ifile):
""" wrkpol functions converts the policy information segment.
Currently the only changes made to the policy segment is to
change Current-Carrier-Type to 0 if it contains a 0 or 1 or
change Current-Carrier-Type to 1 if it contains a 2"""

polwrk = ''
polwrk = polwrk + ifile[0:577]
polwrk = polwrk + ' '
polwrk = polwrk + ifile[588:653]
if ifile[653:654] in ['0','1']:
polwrk = polwrk + '0'
else:
polwrk = polwrk + '1'
polwrk = polwrk + ifile[654:974]

maxcnt = 6
cnt = 0
strstart = 974
while cnt < maxcnt:
if ifile[strstart + 41:strstart + 52] == ' ':
polwrk = polwrk + ifile[strstart:strstart + 72]
else:
polwrk = polwrk + ifile[strstart:strstart + 41]
polwrk = polwrk + ' '
polwrk = polwrk + ifile[strstart + 52:strstart + 72]

strstart += 72
cnt += 1
return polwrk

def wrkdrv(ifile,strstart,maxcnt):
""" wrkdrv function at this point just moves the data as is.
The driver segment is an occurs 6"""

cnt = 0
drvwrk = ''
while cnt < maxcnt:
if ifile[strstart + 23:strstart + 31] <> ' ':
drvwrk = drvwrk + ifile[strstart:strstart + 63]
else:
drvwrk = drvwrk + ifile[strstart:strstart + 63]
strstart += 63
cnt += 1
return drvwrk

def wrkveh(ifile,strstart,maxcnt):
""" wrkveh function does an SQL record lookup to try an select
the correct vehicle in the V1sta make and model files. If the
correct model is found I move V1sta's make model and body
descriptions to the flat file. Currently, I hard code a 1 for
vehicle use. The drive segment is an occurs 6"""

global novehflag
cnt = 0
vehwrk = ''
while cnt < maxcnt:
if ifile[strstart:strstart + 10] == ' ':
if cnt == 0:
print 'No vehicle on quote'
novehflag = True
vehwrk = vehwrk + ifile[strstart:strstart + 133]
else:
vehwrk = vehwrk + ifile[strstart:strstart + 133]
else:
vmake = ifile[strstart:strstart + 10]
vyear = ifile[strstart + 98:strstart + 102]
vvin4_8 = ifile[strstart +53:strstart + 58]
vmodel = ''
vbody = ''
oParmYear.Value = vyear
oParmMake.Value = vmake
(oRS, result) = oCmd.Execute()
while not oRS.EOF:
wvin =
oRS.Fields.Item("VO_VIN_NO").Value.replace('*','.')
wvin.replace('*','.')
wvin = wvin[0:5]
r1 = re.compile(wvin)
if r1.match(vvin4_8):
vmake = oRS.Fields.Item("VA_MK_DESCRIP").Value
vmodel = oRS.Fields.Item("VO_MODEL").Value
vbody = oRS.Fields.Item("VO_DESCRIPTION").Value
vmodelid = oRS.Fields.Item("VO_MODEL_ID").Value
print 'DRC model ' + vmake + ' ' + vyear + ' ' +
vmodel + \
' ' + vmodelid
vehwrk = vehwrk + vmake + vmodel + vbody
break
else:
oRS.MoveNext()
else:
vehwrk = vehwrk + ifile[strstart:strstart + 50]
print 'DRC model NOT FOUND'
vehwrk = vehwrk + ifile[strstart + 50:strstart + 107]
vehwrk = vehwrk + '1'
vehwrk = vehwrk + ifile[strstart + 108:strstart + 133]
strstart += 133
cnt += 1

return vehwrk

def wrkmisc(ifile,strstart):
""" wrkmisc function was a simplistic way to take care of misc
vehicle data which was not formated correctly in the flate file
to begin with."""

return ifile[2582:2774]

def wrkviol(ifile,strstart,maxcnt):
""" wrkviol function is an occurs 6 and is a straight move of
the data"""

cnt = 0
violwrk = ''
while cnt < maxcnt:
if ifile[strstart:strstart + 1] <> ' ':
violwrk = violwrk + ifile[strstart:strstart + 31]
else:
violwrk = violwrk + ifile[strstart:strstart + 31]
strstart += 31
cnt += 1

return violwrk

def wrkaccid(ifile,strstart,maxcnt):
""" wrkaccid function is an occurs 6 and is a straight move of
the data"""

cnt = 0
accdwrk = ''
while cnt < maxcnt:
if ifile[strstart:strstart + 7] <> ' ':
accdwrk = accdwrk + ifile[strstart:strstart + 23]
else:
accdwrk = accdwrk + ifile[strstart:strstart + 23]
strstart += 23
cnt += 1

return accdwrk

def wrkmisc2(ifile,strstart):
""" wrkmisc2 function is again code to pickup data that probably
should have been placed somewhere else but just got tacked on
here"""

return ifile[3638:3666]

def wrkcov(ifile,strstart,maxcnt):
""" wrkcov function moves the coverage data on any coverage segment
which has towing or rental premium it files in the coverage fields
for towing and rental coverage. This is also an occurs 6 field"""

cnt = 0
covwrk = ''
while cnt < maxcnt:
if ifile[strstart + 17:strstart + 19] <> ' ':
covwrk = covwrk + ifile[strstart:strstart + 8]
if ifile[strstart + 92:strstart + 100] == '0 ':
covwrk = covwrk + ifile[strstart + 8:strstart + 12]
else:
covwrk = covwrk + '50 '
if ifile[strstart + 100:strstart + 108] == '0 ':
covwrk = covwrk + ifile[strstart + 12:strstart + 16]
else:
covwrk = covwrk + '20 '
covwrk = covwrk + ifile[strstart + 16:strstart + 108]
else:
covwrk = covwrk + ifile[strstart:strstart + 108]

strstart += 108
cnt += 1

return covwrk

def wrklp(ifile,strstart,maxcnt):
""" wrklp function moves the loss payee data with no changes.
It is an occurs 7. I am not sure if QuotePro messed up on the
occurs
which should be a 6 and V1sta just went with the flow or what. In
addition there are 3 other field that SHOULD have gone in this
segment
but are in the Additional Insured segment which are LP-ZIP-CODE-1,
LP-ZIP-CODE-2, AND LP-CANCEL-DATE."""

cnt = 0
lpwrk = ''
while cnt < maxcnt:
if ifile[strstart:strstart] <> ' ':
lpwrk = lpwrk + ifile[strstart:strstart + 85]
else:
lpwrk = lpwrk + ifile[strstart:strstart + 85]
strstart += 85
cnt += 1
return lpwrk

def wrkai(ifile,strstart,maxcnt):
""" wrkai function moves the additional insured information as well
as the three loss payee fields mentioned in the wrklp function, go
figure. This is an occurs 6"""

cnt = 0
aiwrk = ''
while cnt < maxcnt:
if ifile[strstart:strstart] <> ' ':

aiwrk = aiwrk + ifile[strstart:strstart + 133]
else:
aiwrk = aiwrk + ifile[strstart:strstart + 133]
strstart += 133
cnt += 1
return aiwrk

def wrkmisc3(ifile,strstart):
""" wrkmisc3 just moves the remaining part of the file unchanged"""

return ifile[5707:6435]

# The following code creates a connection object,
# assigns the connection string, opens the
# connection object, and then verifies a good
# connection.

oConn = Dispatch('ADODB.Connection')

oConn.ConnectionString = "Provider=SQLOLEDB.1;" +\
"Data Source=uicesv05;" +\
"uid=aiis;" +\
"pwd=aiis;" +\
"database=auto_mo_001"

oConn.Open()
if oConn.State == adStateOpen:
print "Database connection SUCCEEDED"
else:
print "Database connection FAILED"

# The following code creates a command object,
# assigns the command to the connection object,
# sets the query, creates the parameters objects to
# be passed to the command object and requests the
# query to be prepared (compiled by the SQL system).

oCmd = Dispatch('ADODB.Command')
oCmd.ActiveConnection = oConn
oCmd.CommandType = adCmdText

oCmd.CommandText = """\
SELECT
VA_MK_YEAR,VA_MK_DESCRIP,VO_VIN_NO,VO_MODEL,VO_BODY,
VO_DESCRIPTION,VO_MODEL_ID
FROM D014800 INNER JOIN D014900
ON VA_MK_NUMBER_VER = VO_MAKE_NO AND
VA_MK_YEAR = VO_YEAR
WHERE VA_MK_YEAR = ? AND VA_MK_DESCRIP = ?
"""

vyear = ''
vmake = ''
oParmYear = oCmd.CreateParameter(vyear,adChar,adParamInput)
oParmYear.Size = 4
oParmMake = oCmd.CreateParameter(vmake,adChar,adParamInput)
oParmMake.Size = 10

oCmd.Parameters.Append(oParmYear)
oCmd.Parameters.Append(oParmMake)

oCmd.Prepared = True

# The following code saves the current working directory
# and creates a copy from directory variable and a copy
# to directory variable. We then change the working dir.
# to the copy from dir.
#
# The copy from dir. is the FTP library that the raters
# send the files to. The copy to dir. is where program
# send the changed file to where it is then picked up by
# DRC's interface program and entered into the V1sta
# system.

currdir = os.getcwd()

cfdir = currdir + '\\quotepro\\'
ctdir = currdir + '\\unique\\'

os.chdir(cfdir)

# Next comes what is an infinite loop YES on purpose for
# right now. I intend to eventually replace this code with
# a gui window (as soon as I figure out how). Basicly, the
# way the loop wooks is that it will continue looping
# through the copy from dir (cfdir) looking for files.
# As long as it finds files it will process the files
# and then move them to the copy to dir. (ctdir). If no
# files are found the program goes into sleep mode for a
# short time (currently 15 sec) and then looks in the dir
# again.

while True:
cvtfiles()
# If no files are found in the FTP directory the program goes
# to sleep for 15 seconds
time.sleep(15)

# Closes the SQL record set object
oRS.Close()
oRS = None

# Closes the SQL connection
if oConn.State == adStateOpen:
oConn.Close()

oConn = None

** GUI PROGRAM **

"""This program is an attempt to modularize the lmsface program.
I also will try to document the logic of the program"""

import wx
import os

ID_ABOUT = 101
ID_OPEN = 102
ID_BUTTON1 = 110
ID_BUTTON2 = 120
ID_EXIT = 200

class MainWindow(wx.Frame):
def __init__(self, parent, ID, title):
self.dirname = ''
wx.Frame.__init__(self, parent, wx.ID_ANY, title,
style =
wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)

self.control = wx.TextCtrl(self, 1, style = wx.TE_MULTILINE)

self.CreateStatusBar()

filemenu = wx.Menu()
filemenu.Append(ID_OPEN, '&Open', ' Open a file to edit')
filemenu.AppendSeparator()
filemenu.Append(ID_ABOUT, '&About', ' Information about this
program')
filemenu.AppendSeparator()
filemenu.Append(ID_EXIT, 'E&xit', 'Terminate the program')

menuBar = wx.MenuBar()
menuBar.Append(filemenu, '&File')
self.SetMenuBar(menuBar)

wx.EVT_MENU(self, ID_ABOUT, self.OnAbout)
wx.EVT_MENU(self, ID_EXIT, self.OnExit)
wx.EVT_MENU(self, ID_OPEN, self.OnOpen)

self.button1 = wx.Button(self, ID_BUTTON1, '&Start')
self.button2 = wx.Button(self, ID_BUTTON2, '&Stop')

wx.EVT_BUTTON(self, ID_BUTTON1, self.OnStart)
wx.EVT_BUTTON(self, ID_BUTTON2, self.OnStop)

self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
self.sizer2.Add(self.button1, 1, wx.EXPAND)
self.sizer2.Add(self.button2, 1, wx.EXPAND)

self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.control, 1, wx.EXPAND)
self.sizer.Add(self.sizer2, 0, wx.EXPAND)

self.SetSizer(self.sizer)
self.SetAutoLayout(1)
self.sizer.Fit(self)

self.Show(1)

def OnAbout(self, e):
d = wx.MessageDialog(self, 'A sample editor \n'
' in wxPython',"About Sample Editor",
wx.OK)
d.ShowModal()
d.Destroy()

def OnExit(self, e):
self.Close(True)

def OnOpen(self,e):
""" Open a file """
self.dirname = ''
dlg = wx.FileDialog(self, "Choose a file", self.dirname, "",
"*.*", wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.filename = dlg.GetFilename()
self.dirname = dlg.GetDirectory()
f = open(os.path.join(self.dirname,self.filename),'r')
self.control.SetValue(f.read())
f.close()
dlg.Destroy

def OnStart(self, e):
self.control.AppendText('Start Button Pressed\n')

def OnStop(self, e):
self.control.AppendText('Stop Button Pressed\n')

class myApp(wx.App):
def OnInit(self):
frame = MainWindow(None, -1, "QuotePro/V1sta Interface")
frame.Show(True)
self.SetTopWindow(frame)
return True

app = myApp()
app.MainLoop()
 
S

Steve M

output.write(wrkmisc(ifile,2582))
output.write(wrkviol(ifile,2774,16))
output.write(wrkaccid(ifile,3270,16))
output.write(wrkmisc2(ifile,3638))
output.write(wrkcov(ifile,3666,6))
output.write(wrklp(ifile,4314,7))
output.write(wrkai(ifile,4909,6))
output.write(wrkmisc3(ifile,5707))


Ummm... yuck?
First of all, this program is very hard to understand to somebody who
hasn't written it. ALthough I've never heard of Quote Vista so maybe
that's the problem.

Anyway, if you want to integrate the first program with the second GUI
program, you should convert the first program into a set of functions
that can be called to do everything the first program does.

So basically, take the first program and put everything that's not
already in a function into one. That is, all the code that is at zero
indentation, starting with creating the oConn connection, should be
moved into functions. You can also write a big-mama function that calls
those functions in such a way that it would have the exact same overall
effect as the original script before you moved the code into functions.
You can call this big-mama function 'main'.

Now you can integrate it with the GUI program by importing the first
module from the GUI program and binding the functions to the
appropriate buttons. For example you could bind main to the Start
button you described.

Also, in the first file, you can put the following lines at the bottom,
and it will allow you to run the original script directly to achieve
the same result, while still being able to import it into a second
program and re-use just the functions.

if __name__ == '__main__':
main()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top