A Shortcut For Your Shortcuts

April 2nd, 2008 by Patrick Boucher - Viewed 7042 times -




When working with XSI in a facility I often use Python modules to better package my code and allow easy reuse of key parts in the different tools that are developed. These modules I usually keep in a location on the main drive of the workstations, for example: C:\<facilityName>\libs\python.

I’ll also put in place a system to push central library changes to the local computers and insert the library location in the PYTHONPATH environment variable.

The XSI Wiki has a great page on the pros and cons of the module approach. One of the cons is that the Application global variable is only accessible in your script files and plugin files and not in your modules.

In the past I would put the following code at the top of my various modules:

1
2
3
4
import win32com
from win32com.client import constants as c
xsi = win32com.client.Dispatch('XSI.Application').Application
log = xsi.Logmessage

Following this would be a bunch of other shortcuts and dispatch commands for XSIUtils, XSIUIToolkit, XSIMath, etc…

Being tired of inserting these lines at the header of every module and a subset of this code (for shortcuts) at every script or plugin, I decided to centralize them and move them to their own module.

The library structure looks like so:

../libpath/
    vg/
        xsi/
            __init__.py
            xsiModule1.py
            xsiModule2.py
            [...]

In the __init__.py file I put the following code:

1
2
3
4
5
6
7
8
9
10
11
12
import win32com
from win32com.client import constants as c
xsi = win32com.client.Dispatch('XSI.Application').Application
log = xsi.Logmessage
# [... more shortcuts and dispatch commands ...]
 
def getShortcuts(g):
    g['win32com'] = win32com
    g['c'] = c
    g['xsi'] = xsi
    g['log'] = log
    # [... more shortcuts and dispatch commands scope transfers...]

This allows me to benefit from the shortcuts in the rest of the __init__.py file where some general XSI functions are kept but also start my other modules, scripts and plugins with the following two lines:

1
2
import vg.xsi as vx
vx.getShortcuts(globals())

By providing the getShortcuts function with a dict representing the global scope of my module, script or plugin, the function can edit the members of the scope and give me all the necessary symbols.

Another stupid trick rears it’s head! ;)
Happy scripting!

Comments are closed.