O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Executing Scripts

Quite often the user wants to execute simple scripts. If the user has created a simple script in a file on disk, it can be run with the built-in function execfile ( file[, globals[, locals]] ). This is broadly equivalent to the exec statement discussed earlier, except that it’s a function, and it takes filename as an argument, processing the entire contents. To expose this, we’ve implemented a new method of COMBookSet , which takes the filename as a single argument, and calls execfile( filename , self.userNameSpace ):

def execFile(self, filename):
    if type(filename) not in [type(''), UnicodeType]:
        raise Exception(desc="Must be a string", \
                          scode=winerror.DISP_E_TYPEMISMATCH)
    execfile(str(filename), self.userNameSpace)

VB provides a rich-text editor component that makes it easy to create an editor, so we’ve added yet another form to our application called frmScriptEditor . This has a single editing region and a menu. We provided menu options to open and save files, and it keeps track of the filename and whether the text has changed. We won’t cover those functions here. It also has a menu option to run a script, which is straightforward to implement:

Private Sub mnuScriptRun_Click()
    mnuScriptSave_Click
    If Saved Then
        On Error GoTo mnuScriptRun_Error
        frmMain.BookServer.execFile FileName
        On Error GoTo 0
        frmConsole.UpdateOutput
    End If
    Exit Sub
    
mnuScriptRun_Error:
    MsgBox "Error running script:" + vbCrLf + vbCrLf + Err.Description
End Sub

We handle errors, since the user ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required