Using the SolidWorks API with Python is not as easy as it should be.
Generating modules from the type libraries is easy enough with makepy:
makepy.py sldworks.tlb
makepy.py swconst.tlb
As is using these to start up SolidWorks.
from win32com.client import gencache,Dispatch
from win32com.client import constants
sldworks = gencache.EnsureModule('{83A33D31-27C5-11CE-BFD4-00400513BB57}', 0, 15, 0) # sw2007
swconst = gencache.EnsureModule('{4687F359-55D0-4CD3-B6CF-2EB42C11F989}', 0, 15, 0) # sw2007
sw = sldworks.SldWorks( Dispatch( 'SldWorks.Application' ) )
But you soon hit problems when you want to open a model with OpenDoc6. This code:
model, errors, warnings = sw.OpenDoc6( 'cube.sldprt', constants.swDocPART, constants.swOpenDocOptions_Silent, '' )
triggers this exception:
pywintypes.com_error: (-2147352561, 'Parameter not optional.', None, None)
The problem turns out to be that the method generated with makepy has incorrect default values. In the definition below Errors and Warnings should have deafult values of pythoncom.Missing.
def OpenDoc6(self, FileName=defaultNamedNotOptArg, Type=defaultNamedNotOptArg, Options=defaultNamedNotOptArg, Configuration=defaultNamedNotOptArg, Errors=defaultNamedNotOptArg, Warnings=defaultNamedNotOptArg):
To fix this I have used the Python introspection methods to rewrite the default arguments.
import pythoncom
import new
method = getattr( sldworks.ISldWorks, 'OpenDoc6' )
arg_list = list( method.func_defaults )
arg_list[ -1 ] = pythoncom.Missing
arg_list[ -2 ] = pythoncom.Missing
new_function = new.function( method.func_code, method.func_globals, method.func_code.co_name, tuple( arg_list ) )
new_method = new.instancemethod( new_function, None, sldworks.ISldWorks )
setattr( sldworks.ISldWorks, 'OpenDoc6', new_method )
I have created a generic method that could be used to fix up more than just OpenDoc6. You can download it here: swfix.py It is used like this:
from win32com.client import gencache,Dispatch
from win32com.client import constants
from swfix import fix_swtlb
sldworks = gencache.EnsureModule('{83A33D31-27C5-11CE-BFD4-00400513BB57}', 0, 15, 0) # sw2007
swconst = gencache.EnsureModule('{4687F359-55D0-4CD3-B6CF-2EB42C11F989}', 0, 15, 0) # sw2007
fix_swtlb( sldworks )
sw = sldworks.SldWorks( Dispatch( 'SldWorks.Application' ) )
Currently it only fixes OpenDoc6, but I hope to include other methods over time. Of course help in doing this is most welcome.