0% found this document useful (0 votes)
254 views

Python VFP1

This document introduces Python as an alternative programming language to Visual FoxPro that allows applications to run on multiple platforms. It provides an overview of Python, how to install it, and a short tutorial demonstrating how to access and manipulate Visual FoxPro database tables from Python. The tutorial shows basic Python syntax and functionality through interactive examples in the Python IDLE IDE.

Uploaded by

denatma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
254 views

Python VFP1

This document introduces Python as an alternative programming language to Visual FoxPro that allows applications to run on multiple platforms. It provides an overview of Python, how to install it, and a short tutorial demonstrating how to access and manipulate Visual FoxPro database tables from Python. The tutorial shows basic Python syntax and functionality through interactive examples in the Python IDLE IDE.

Uploaded by

denatma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

ExampleSourceCode:http://www.paulmcnett.com/vfp/09MCNESC.

zip
ThisarticleoriginallyappearedintheSeptember2003issueofFoxTalk.
Ifyouenjoythisarticle,pleaseconsidersendingaPayPaldonationtop@ulmcnett.com.Thanks!

ExploringPythonfromaVisualFoxPro
Perspective
PaulMcNett

VisualFoxProisquitecapableinalmostallaspects,exceptforapplicationdeploymentaccordingtoMicrosoft,youmay
onlydeployyourapplicationstoWindowssystems.Feelingsomewhatlimitedbythissituation,IdiscoveredPython,an
opensourceprogramminglanguagethatisacompellingchoiceforseasonedVisualFoxProdevelopersanditrunson
multipleplatforms!Inthisarticle,I'llintroduceyoutoPython,andshowyouhowtoaccessVisualFoxProdatawithit.

ManyVisualFoxProdevelopersfeelthattheirchoicesofdevelopmentenvironmentsareeffectivelylimited
toVisualFoxProor.NETVisualFoxProbecausethatiswhattheyknow,and.NETbecauseitis
compelling,capable,andrichwithfeaturesandanastronomicaladvertisingbudget.Bothoftheseoptions
linkagainsttheWindowsGUI,andarethereforelimitedtorunningontheWindowsplatform(unlessyou
wanttouseaworkaroundsuchasWineoravirtualmachinesuchasWin4LinorVMWare).Thislimitation
isobviouslybydesign.Otherlanguagesanddevelopmentenvironmentsexist,separatefrom.NET,suchas
thevariousflavorsofC,C++,andJava,thataremultiplatformcapable,butinmyquestforamultiplatform
programminglanguage,onerosetothetoppreciselybecauseofitssimilaritiesinlotsofwaystothe
experienceofprogramminginFoxPro.I'dliketosharewhatI'velearnedaboutPython,andhowthis
knowledgemayapplyvisavisVisualFoxPro.
YouareprobablyaskingwhyshouldIcare,whyshouldIlearnyetanotherlanguage?TothatI
mustanswer:justhavealook,followmytutorialandseewhatPython'sstrengthsandweaknessesare.Ifit
isn'tforyou,youhaven'tinvestedmuchtofindthatout.Butifyouendupappreciatingit,asIknowyou
will,you'llhaveanothervaluabletooltoputinyourkit.
PythonataGlance

Sportingasnakeicon,PythonwasactuallynamedaftertheMontyPython'sFlyingCircusBBCtelevision
show,byitscreator,GuidovanRossum,startinginthelate1980's.Itcomeswithanenthusiasticcommunity
ofverysmartpeoplethatareonthewholeveryhappytosharetheirrecipesandhelpnewbiesgetstarted.
Pythonisaninterpretedlanguagewithanelegantandreadablesyntax,andlikeVisualFoxProyou
canmixandmatchOOPwithfunctionalprogramming,allvariablesareineffectvariants,andthereisa
strongandflexiblebutquitedifferentdatamodel.Pythonconsistsofthecoremodulesandisaugmented
byadditionalmodulescontributedbydevelopersallovertheworld.
Pythoncomeswithaliberalopensourcelicense,whichmeansthatyouarefreetomodifyand
redistributethecodeprettymuchasyouseefit.ThePythoninterpreteriscompiledCCode,anddoesn't
haveanydependenciesonanyGUI,sothereforeisquiteportabletoallknownplatforms,evenincluding
DOS,olderversionsofWindows,andembeddedsystems.Writeyourcodeonceonagivenplatform,andas
longasyouhaven'tlinkedagainstanymodulesthatareplatformdependent,yourprogramwillexecuteon
anyotherplatform.WhilemostPythonprogramsarebuilttorunonWindowsandLinux,MacintoshOSX
isalsowidelysupportedandanyPythonprogramcanbemadetorunonmanyotherplatformsaswell.
ErrorhandlingiseasywiththenowubiquitousTRY...CATCH...FINALLYblockswhichcanbe
nested.Therearestandardexceptionsthatcanbecaughtorthrown,andyoucanmakeyourownaswellby
simplysubclassingtheExceptionclass.Unittestinganddocumentationaresonaturalandeasythatyou
actuallyhavetotrytoignoretheseimportantfeatures.
Pythonisstrictcase:capitalizationmattersinyoursourcecode.However,dependingonthe
operatingsystemyouarerunningiton,capitalizationmayormaynotmatterwithregardtofileand
directorynames.
Functionsarefirstclassobjects,whichmeansthatyoucangetanobjectreferencetoafunction
(eitherastandalonefunctionoramethodofaclass),andpassitaroundtootherfunctions.Garbage
collectionhappensautomaticallyinthebackground,andcanbeoverriddenifneeded.

Sourcecodeisplaintext,whichmeansyoucanuseyourfavoriteeditor,andPythonsourcefiles
(scripts)byconventionhavea.pyextension.Compilationtobytecodehappensinthebackgroundbythe
Pythoninterpreterasneeded,whichgenerates.pycor.pyofiles,dependingonhowyouhaveitset.Youmay
also,asinFoxPro,fireuptheinteractivePythoninterpreter,andexecutestatementslinebyline.The
interactiveinterpreterisactuallymorecapablethanVisualFoxPro'scommandwindow,inthatyoucaneven
executecontrolstructuresanddefineentireclassesorfunctions.
Python,unlikeVisualFoxPro,doesnotcomewithanygraphicalwidgetsforconstructing
Windowsapplications.Itis,however,distributedwithamultiplatformGUItoolkitcalledTkinter,which
youarefreetouse.InmyopiniontherearebetterchoicesthanTkinter(PyQtandwxPythontonamethe
toptwo),butmypointhereisthatPythonprogramsaresimplescriptsthatcanoptionallylinktoaGUI.Itis
nicenotcarryingalongtheGUIbaggagewhenagivenprogramdoesn'tneedit,anditisveryliberatingto
beabletochooseforyourselftheGUIthatworksbestforyou.
PythoncomeswitharudimentaryIntegratedDevelopmentEnvironmentcalledIDLE,althoughI
usuallyjustusethecommandlinebecauseIfindthatsimplerandmoreefficientformypurposes.I'llutilize
IDLEinthistutorialsincemostWindowsdevelopersaremorecomfortableusingaGUIthanacommand
line.
InstallingPython

PythoniseasilyinstalledonWindowsbydownloadingandrunningtheinstallerat
http://www.python.org/ftp/python/2.2.3/Python2.2.3.exe.WhiletherestofthisarticleassumesaWindows
installation,youmayinstallitonotherplatformsaswellbyfollowinglinksat
http://www.python.org/download.Makesureyouleaveallinstallationoptionscheckedsothatyouhave
everythingyouneed.Pleasealsoinstallthewin32allextensions
(http://starship.python.net/crew/mhammond/downloads/win32all152.exe),whichincludesfunctionalityfor
Windowsdevelopment.Pythonandthewin32allextensionsarecompletelyfree,asinfreedomandasin
beer.
AfteryouinstallPythonandthewin32allextensions,I'llguideyouthroughashorttutorialand
showyouhoweasyitistotalktoFoxProdatafiles.Alongthewayyou'lllearnPython'sbasicdatatypes,
controlstructures,andOOPimplementation.
AShortTutorialDataAccessinPythonandVisualFoxPro

ThistutorialwillshowhowtousePythontomanipulatetablescreatedinVisualFoxPro.Alongtheway,
you'llbeintroducedtoPython'sbasicfunctionality.Intherealworld,InolongerusenativeVisualFoxPro
tables,butratherchoosetouseMySQL(orotherdatabaseservers)onthebackend.FromVisualFoxPro,I
connecttoMySQLusingtheMyODBCdriver,andfromPython,IconnectusingtheMySQLclientlibrary
directly.Forsimplicityinthisarticlethough,I'lljustusenativeVisualFoxProtablesandthenmanipulate
thosetablesbothfromVFPandPython.
Thefirstthingyou'llwanttodoismakesureyourPythoninstallationwassuccessful.Whilethere
aremanywaystousePython,I'llguideyouthroughusingthePythoncommandlineinterpreteras
implementedbyIDLE,thePythonIDE.HavealookinyourWindowsstartmenu,underPrograms/Python
2.2.ClickontheshortcutlabeledIDLE(PythonGUI).DoingthiswillbringupawindowtitledPython
Shell,completewithacommandinterpreterandablinkingcursor.Thecommandpromptis>>>.To
aquaintyouwiththemostbasicPythoncommands,followtheseexamples:
>>>printhelloworld!#thestringisoutput
helloworld
>>>helloworld!#astringobjectisoutput
'helloworld'
>>>1+2#Addition
3
>>>12#Subtraction
1
>>>75*57#Multiplication
4275
>>>1/2#Divisionofinteger
0
>>>1.0/2#Divisionoffloat
0.5
>>>breakfast=eggs#bindingnametostring
>>>count=3#bindinganothernametointeger

>>>#simpleoutputformatting/linecontinuation:
>>>printforbreakfastyou'llhave%d%s.\
%(count,breakfast)
forbreakfastyou'llhave3eggs.
>>>importsys#importingexternalmodule
>>>sys.platform
'win32'
>>>importodbc#testifwin32allisinstalled
>>>defmyFunction(string):
printMyFunction:,string
returnyes
(pressreturntwiceheretogetthepromptback)
>>>printmyFunction(hereIam!)
MyFunction:hereIam!
yes
>>>printmyFunction
<functionmyFunctionat0x8176084>

Okay,sobasicallythePythoninteractiveinterpreterisyourfriend.Itisgreatforquicklytryingthingsout
andgettingusedtoPython'ssyntax.(Hmmmm,soundfamiliar?Kindalikeadotprompt?OrtheVisual
FoxProCommandWindow?)Andyougetadditionalbenefitsfromusingtheinteractiveinterpreterwith
IDLE:namelysyntaxcoloringandfunctionargumentToolTiphelp.Ifyounoticed,youlearnedseveral
thingsintheabovesession:commentscanappearonalineoftheirownorinline,alinecanbecontinued
withthebackslashcharacter,normalPythonscriptscanbeimportedintootherPythonscriptsasmodules,
thebasicprintoutputfunctionalityisadequateforquicktesting,andfunctionsarefirstclassobjectsand
thuscanbepassedtootherfunctions.Ifyoudidn'tgetanyerrorsimportingtheodbcmodule,youareready
tocontinuewiththistutorial.
MygoalistointroduceyoutothesimplicityandeleganceofPython,andI'lldothisbyshowing
youhowyoucanaccessandmanipulatedatabasetablesfromPythoncode.I'llwalkyouthroughthedesign
ofsometesttablesfromVFP,accessingandmanipulatingthetablesfromVFPwiththeFoxProODBC
driver,andthenaccessingandmanipulatingthetablesfromPythonusingthesameODBCdriver.
Firstofall,makesureyouhavetheVisualFoxProODBCdriverinstalled(opentheODBC
Administrator,gotothedriverstab,andlocatethedriver.Notetheexactnameofthedriver,whichyou'll
needwhenyouentertheconnectstringlater.Myversionis6.01.8629.01,andthenameisMicrosoft
FoxProVFPDriver(*.dbf).Ifyoursisnameddifferently,you'llhavetosubstituteyournameinmy
examples.
Timetocreatethetable.FireupVisualFoxPro,andfollowalonginthecommandwindow:
mkdirc:\temp\pytest
cdc:\temp\pytest
createtablemenu(iidi,citemc(32),;
npricen(8,2))
insertintomenu(iid,citem,nprice)values;
(1,Pancakes,4.50)
insertintomenu(iid,citem,nprice)values;
(2,CoffeeCake,2.89)
insertintomenu(iid,citem,nprice)values;
(3,TofuScramble,5.00)
use
*connectusingODBC:

cString=[driver=];
+[{MicrosoftFoxProVFPDriver(*.dbf)};];
+[SourceType=DBF;SourceDB=c:\temp\pytest\]
iHandle=c:/temp/pytest/"
*iHandleshouldcontainapostivevalueifit
*returnsa'1'value,itmeansthecommand
*failed
=SQLEXEC(m.iHandle,select*frommenu)
BROWSE

Ifyouseeyourthreerecordsinasqlcursorcalledsqlresult,thenallisasitshouldbe.Timetotrythe
samethingfromPython.

Beforegoingon,IshouldbackawayatthispointandexplainthatPythonconsistsofacorethatis
extensiblebyimportingexternalmodules.ThesemodulesmayhavebeendistributedwithPython,orthey
mayhavecomefromoneofhundredsofdevelopersworldwide,ortheymayhavebeenwrittenbyyou.The
pointI'mmakinghereisthat,unlikeVFP,Pythondoesnotloadupalotofbaggagethatyoumayormay
noteveruse,butinsteadleavesituptoyoutoimportthemodulesthatyourequire.Indeed,yougetto
choosethemodulesthatworkbestforyou,insteadofrelyingononevendortomaketheonecorrectchoice
foryou,orrefusingtoprovidefunctionalitythatyouneed.
Accessingdatabasesrequirestheimportingofanappropriatedriverforthedatabaseinquestion,
andtomakeitalesslowlevelofanexperienceI'veborrowedarecipefromThePythonCookbookcalled
'LazyDB',writtenbyJohnB.Dell'Aquila,andwrappeditwith2layersofmyownmodules,onethat
definesadbAccessbaseclass,andoneexamplesubclassthatcanbeusedtoaccessVFPtables.Other
subclassescouldbemadetoaccessotherbackenddatabases,suchasMySQLorMicrosoftSQLServer.
Anyway,thereare3filesinthedownloadsectionthatyouneedtosaveforthetutorialtowork.
Theyare:lazydb.py,dbaccess.py,anddbaccess_vfp.py.Savethemtoc:\temp\pytestcode\.dbaccess_vfp.py
containsasubclassofdbAccess,whichisdefinedindbaccess.py.dbaccess.pyinstantiatestheConnection
classasdefinedinlazydb.py.
Takealookatthesethreefilesinatexteditor(hint:openIDLE,thenFile/Open,andviewthefiles
thatway,asyougetthebenefitsofsyntaxcoloring).Notethateveryscriptexceptforlazydbhasanimport
statement.dbaccess_vfpimportstheodbcdriver,becausethatishowtoconnecttoVFPtables.Formy
projects,Iactuallyuseadbaccess_mysqlscriptthat,insteadofimportingodbc,importsMySqlDbwhich
connectsdirectlytoMySQLwithouttheneedforODBC.BoththeMySQLandtheVFPscriptsaccessthe
commondbaccessandlazydbmodules.
Anyway,takealookatthecodeinthesethreefilesasyouarenewtoPython,youwon't
completelyunderstandit,butyoushouldnoticethatthecodeisreadableandtheclassdefinitionsare
simple.Noticeatthebottomofdbaccess_vfp.py,thereisablockoftestcode.Thisis,ineffect,awayof
includingunittestingwithyourmodules.Thecodewillonlyexecutewhenrunasscript(bytyping'python
dbaccess_vfp.py'attheDOScommandline),butwillnotexecutewhenimportedfromanotherfile.Itis
verysimilartotheconventiongoodVFPdevelopershaveadoptedofputtingunittestcodeintheirprogram
classesthatwillexecutewhenyourunthecodeasaprogram,butnotwhenyouinstantiateaclassfromthat
programfile.ThedifferenceisthatinVFP,youwouldputsuchtestcodeatthetop,butinPythonitmustgo
atthebottom.Justforkicks,whydon'tyourundbaccess_vfp.pyandseeifeverythingisworkingcorrectly.
OpenupaDOScommandline(cmd.exe)anddothefollowing:
c:
cdc:\temp\pytestcode
pythondbaccess_vfp.py

Ifyousawthetestoutputalongwiththe3menuitems,everythingisworkingjustfine.Ifyougota
TraceBackmessage(Python'sdefaulterrorhandler),youprobablyneedtoeditdbaccess_vfp.pytochange
theconnectstringtoconformtoyourodbcsetup.Itishardcodedintherenotnormallyagreatpracticebut
itdoesjustfineforthisexample.Changeitappropriatelytomatchyoursetup.IfyougotaWindows
messagethatthepythonexecutablecouldnotbelocated,thenyouneedtomanuallyaddthePython2.2
programdirectorytoyoursystempath.Alternatively,ifthe.pyextensiongotregisteredcorrectly,youcan
probablygetawaywithsimplytyping:
dbaccess_vfp.py

Okay,sothescriptruns,provingthatyou'vegottendataoutoftheVFPtable.Itismorefuntointeractwith
tables,soitistimetostartIDLEagainandfollowalonginthePythonshell.I'llbeimportingthe
dbaccess_vfp.pymodule,whichisstillsittinginc:\temp\pycode.Becauseitisn'tinPython'ssearchpathfor
modules,I'llneedtoaddthepathmanually.Whilethereareotherwaystoachievethesameendresult,this
oneintroducesyoutoabasicPythontype:theList.
PythonisparticularlywellsuitedfordealingwithdatabecauseofitsList,Tuple,andDictionary
datatypes.Theseareallsequences,andsequencescancontainothersequences,resultinginapowerful
matrixofpossibilities.Alistisamutablesequenceofitems,andisspecifiedbyusingsquarebrackets([]).
Contrastthistoatuple,whichisanimmutablesequenceofitems.Atupleisdesignatedbynormalparens

().Listsareagreatwaytohold'records',wherebyeach'record'isanotherlistof'fields'.Anyway,the
pathingissue:
>>>importsys#basicsystemfunctions
>>>printsys.path
(Iomittedtheresults,butdothisyourself,
andyou'llseealistofstrings)
>>>#appendourpath:
>>>sys.path.append(c:\\temp\\pycode)

Nowthatyouhavethepathsetup(didyounoticethatthelistisactuallyanobjectwithanappend()
method?)youcanfollowalongwiththefollowinginteractivesessiontoreadfromandmanipulatethetest
data:
>>>#importintotheglobalnamespace:
>>>fromdbaccess_vfpimport*
>>>#getarecordset:
>>>menu=dbVFP().dbRecordSet(select*
frommenu)
>>>#showalltherecords(notetheclean
>>>#iterationstyle):
>>>foriteminmenu:
printitem.citem,item.nprice
(twoCR'stoexittheiterationblock)

Youshouldseeonerecordperline.Ok,timetohavesomefunbyupdatingandinsertingrecords:
>>>#thistimegetapersistentobjectreference
>>>#todbVFP:
>>>vfp=dbVFP()
>>>vfp.dbCommand(updatemenusetcitem=
'PancakesandSpam'whereiid=1)
>>>#thistimedefineafunctionwecancall
>>>#overandoveragain:
>>>defshowAll():
menu=dbVFP().dbRecordSet(select*from
menuorderbyiid)
forrecordinmenu:
printrecord.iid,record.citem,\
record.nprice
>>>#nowwhenwechangesomething,wecanjust
>>>#callshowAll():
>>>vfp.dbCommand(insertintomenu

(iid,citem,nprice)values

(4,'RiceCakesandWater',14.50))
>>>showAll()

Playaroundinteractivelyforawhile,andstartexperimentingwithwritingyourowncustomscripts.You
maynotbeallthatexcitedyet,becauseyou'venoticedthatsofaritsbeenalltextoutput,nofamiliar
graphicaluserinterface.Thiswastokeepthetutorialsimple,tointroduceyouPythonbyshowingyouone
waytoaccessFoxProtables.Restassured,therearemanywaystocreateprofessionalGUIapplicationswith
Python.Justsoyoudon'tfeeltotallyleftoutinthecold,hereisalittleteasertoshowyouhoweasyitcan
betoaddagraphicalinterfacetoyourapplication(enterthiscodeinthePythonShellinteractively,orif
youarefeelingmoresureofyourself,makeitintoascriptandthenexecuteit):
importsys,Tkinter
Tkinter.Label(text=Enoughspamforya?).pack()
Tkinter.Button(text=Bye,command=sys.exit).pack()
Tkinter.mainloop()

PythonResources

Pythonissupportedbyacommunityofenthusiasticvolunteers,inacademiaandtheITindustry,from
aroundtheworld.AgreatplacetostartisattheofficialPythonwebsite,athttp://www.python.org.There
areplentyoftutorialsandlotsofdocumentationtheretokeepyoubusylearningthisexcitinglanguage.
Thereisalsoamailinglist/UseNetgroup(pythonlist@python.org/comp.lang.python)thatrangesfrom
newbietoultratechnicalandthatI'vefoundquitefascinating.Thereareanumberofbooksavailable,of

whichIcanhighlyrecommendPythoninaNutshell,byAlexMartelli,O'Reilly2003asagreatdesktop
referenceandPythonCookbook,editedbyAlexMartelliandDavidAsher,O'Reilly2002,whichcontains
recipes(howto's)fromthePythoncommunity.
PythonandVisualFoxProcanworkwelltogetherinsituationswhereyouhaveadesktopapplicationanda
webapplicationaccessingthesamedata.ThedesktopapplicationcanbewritteninVisualFoxProwhilethe
webapplicationcanbedoneinPython.ItcanbedifficulttodeployaVFPapptothewebbecauseofthe
loadVFPtendstoputontheserverunlessyouhaveadedicatedserverforyourVFPwebapp,you'll
probablybebetterservedwithaPythonwebapponanApachewebserver.Or,ifyoufindthatyouneedto
deployyourdesktopapplicationtoplatformsotherthanthelatestversionofWindows,youcanconsider
rewritingitinPython,coupledwithagraphicaltoolkitsuchasQtorwxPython.Whenitcomesto
developmenttools,therearemanyalternativesoutthere,andinmyobservationsPythonisworthalook.
PaulMcNettisanindependentsoftwareconsultantinHollister,California.Whiledesigningdesktopandweb
applicationsusingVisualFoxProisstillhisprimaryfocus,heisalsousingdevelopertoolsfromtheopensource
community,includingPython,todeploytotheOSX,Linux,andWindowsplatforms.Hecanbereachedbyemailat
p@ulmcnett.comorbyphoneat831.636.9900.

You might also like