Skip to main content

How to use pySW - a Python Solidworks VBA API wrapper

 Recently I found a python package called "pySW" to be useful for those who are interested in both Solidworks API programming and python language. If you are familiar with Visual Studio Code and shell command in the terminal, you can easily install and play with it. You may want to visit its author's github repository and try his sample test program. I modified a little to read the lens template and generate the variants. It is almost identical to his box generation sample program. It looks like pySW project has never been updated for last 3 years though. Once the package is installed, you need modify a few lines to make it work. Let me explain one by one. 

The web page link

Package installation and test program workaround

  • Install pySW
    Run the following command. You should install other dependent python packages. 
    pip install pySW
    
    
  • Update method names in commSW.py and main.py
    You can browse your local python site-package folder of pySW and your local copy of test/box folder respectively. Change getGlobalVariables with getGlobalVars, updatePrt with update, and saveAssy with save.
  • Customize test program main.py for my own lens generation
    This is the complete main.py python code of lens model generated from template model. You can double-check the pre-requisite update to run this program successfully from the initial comment lines shown below.  
    """
    As of June 2, 2023
    
    1 Python package modification
    Install pySW 1.4 and modify commSW.py at
    C:\\Users\\your-computer-username\\AppData\\Local\\Programs\\Python\
    \\Python311\\Lib\\site-packages\\pySW
    
    Line 122 getGlobalVariables to getGlobalVars
    Line 140, 190 updatePrt to update
    
    
    2 Sample file modification
    Copy and modify 
    https://github.com/kalyanpi4/pySW/blob/master/tests/box/main.py
    
    Line 17 getGlobalVariables to getGlobalVars
    Line 48 updatePrt to update
    Line 49 saveAssy to save
    """
    
    from pySW import SW
    from pyDOE import lhs
    from scipy.stats.distributions import norm
    import psutil
    import time
    import shutil
    import pandas as pd
    
    partName = r'Lens-DCX.SLDPRT'
    
    if "SLDWORKS.exe" in (p.name() for p in psutil.process_iter()) is False:
        print('starting SLDWORKS')
        SW.startSW()
        time.sleep(10)
    
    SW.connectToSW()
    
    cwd = psutil.os.getcwd()
    SW.openPrt(cwd+'\\template\\'+partName)
    
    var = SW.getGlobalVars()
    
    variables = []
    for key in var:
        variables.append(key)
    
    design = lhs(len(var.keys()), samples=3)
    means = [100, 100, 40, 8]
    stdvs = [10, 10, 5, 1]
    
    for i in range(len(var.keys())):
        design[:, i] = norm(loc=means[i], scale=stdvs[i]).ppf(design[:, i])
    
    analysisDir = psutil.os.getcwd()+'\\analysis'
    if psutil.os.listdir(psutil.os.getcwd())[0] == 'analysis':
        shutil.rmtree(analysisDir)
        psutil.os.mkdir(analysisDir)
    else:
        psutil.os.mkdir(analysisDir)
    
    for i in range(len(design)):
        for j in range(len(variables)):
            SW.modifyGlobalVar(variables[j], round(design[i][j]), 'mm')
            SW.update()
            SW.save(analysisDir+'\\', str(i), 'SLDPRT')
    
    df = pd.DataFrame(design, columns=variables)
    df.to_csv(psutil.os.getcwd()+'\\params.csv')
    
    
  •  You may add any extra code lines to detect "analysis" folder and manage the result folders more efficiently. I simply focused on the modeling automation itself. Right now, you have to delete that folder before running the program. 
 This is my vscode interface and template model screenshot. Notice the equation variables in the template part model. The order of them matches that of variables in the code. 
 I wonder python library functionality concerning 3D object handling can be transferred to Solidworks COM easily in this way. If we need all wrapper classes and methods corresponding to VBA matrix manipulation functions, it must become a time-consuming and tedious project. If so, I wouldn't continue. Instead, I would check python capability in Fusion 360 personal use API. 

Comments

Popular posts from this blog

How to Fix Microsoft Mouse 3500 Wheel Scrolling Issue - Jump or Random Movement

 It is hard to deny the fact that a mouse is one of most important peripheral devices of a desktop or laptop computer - inexpensive and portable input device. Personally I don't want to replace it with other alternatives such as trackpad, trackball or trackpoint.   Microsoft 3500 is one of reasonably priced wireless mouse products available in the market. You may experience small or large troubles while using any mouse products. I experienced jumping or random movement while scrolling the web pages or zooming a object in and out in 3D software such as Solidworks or Blender. The quick and easy actions we can take is to replace battery, check other software, restart the computer, reinstall the mouse driver, switch USB port, and so on. Since my gut told me it would be a physical issue, I decided to open the mouse and check the wheel.   First I thought simply cleaning dust around the wheel would be sufficient. According to previous experiences of other mouse product...

Solidworks API Programming: Macro Recording and Editing

Solidworks API Programming, Part 1:  Automatically generated VBA source code analysis Let's start Solidworks API Programming with macro source code analysis. I just explain what I have done in person. Although I have not read the book, "Automating SOLIDWORKS 2006 using MACROS ( http://www.amazon.com/Automating-SOLIDWORKS-2006-using-MACROS/dp/1585032638 )", I think it could be a good reference for serious users. If you know better or best book for Solidworks API Programming, please leave the comment. 1. Macro Recording: Tools - Macro - Record This is the common function of MS-based programs which support VBA just like Excel. This function record the user action itself converting it into VBA source code. 1) Just click Tools - Macro - Record 2) Do what you want to do within solidworks like sketching and extruding 3) After finishing your work, just click Stop 4) Save window pops up. Write the filename and save it. 2. Macro Editing: Tools - Macro - Edit... L...