473,385 Members | 1,468 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Advice on this code

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_BOD Y,
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_RESIZ E)

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()

Oct 12 '05 #1
1 1953
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()

Oct 12 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

75
by: Howard Nease | last post by:
Hello, everyone. I would appreciate any advice that someone could give me on my future career path. Here is my situation: I am a bright Junior in a very well-respected private high school, taking...
3
by: Andy Dingley | last post by:
I've just started on a new project and inherited a huge pile of XSLT (and I use the term "pile" advisedly !) It runs at glacial speed, and I need to fix this this. Platform is MSXML 4 / ASP ...
3
by: theintrepidfox | last post by:
Dear Group I'd be grateful if you can give me some advice on the following. An application I wrote uses an MSDE backend and I wonder whether there's a way (even for the system administrator) of...
11
by: ma740988 | last post by:
I'm perusing a slide with roughly 12 bullets spread across 3 pages. Each bullet reflects 'advice'. I'm ok with all but 1 bullet, more specifically the bullet that states: " Avoid the STL unless...
6
by: | last post by:
I am starting out my transition from classic asp to .NET and was hoping some advice could be offered on using Webmatrix to do my initial small asp-like, xml and flash embedded projects. ...
13
by: Alan Silver | last post by:
Hello, MSDN (amongst other places) is full of helpful advice on ways to do data access, but they all seem geared to wards enterprise applications. Maybe I'm in a minority, but I don't have those...
7
by: John Paul | last post by:
I'm thinking of building an e-commerce site in php. Anyone got any advice in building one? What is the best way to implement a payment system? Are any legal issues involved? Thanks,
9
by: Duncan Smith | last post by:
Hello, I find myself in the, for me, unusual (and at the moment unique) position of having to write a web application. I have quite a lot of existing Python code that will form part of the...
232
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first...
2
by: lmaurer | last post by:
Hi all, I have been charged with learning how to create web pages that will function as data capturing tools. From the research I have done, it looks like I need to learn ASP.net and SQL Server...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.