Worksession manipulation from Grasshopper?

You can get around the missing SDK worksession functionality using the command line. Here is a snippet form a Grasshopper python component i use to automate creating worksessions:

"""attaches a list of files to the current worksession
    Inputs:
        P: file paths to attach to worksession
    Output:
        R: True if no errors"""

__author__ = "Dharman.Gersch"
__version__ = "2018.08.22"

ghenv.Component.Name = "Worksession.Attach"
ghenv.Component.NickName = 'WS.Attach'
    ghenv.Component.Message = "" #'VER ALPHA 0.0.1\n 2018_07_11'
    ghenv.Component.Category = "worksession"
ghenv.Component.SubCategory = "1"

import rhinoscriptsyntax as rs
import Rhino

#P is a list of filepaths to attach to worksession
for p in P:
    #command must be surrounded with '' so that file path can e surrounded with ""
    #this ensures that paths with spaces still work
    rs.Command('-Worksession Attach "{}" _Enter'.format(p))

#useful stuff here: Rhino.DocObjects.Worksession
doc = Rhino.RhinoDoc.ActiveDoc
WS = doc.Worksession
paths = WS.ModelPaths

#R is used downstream. only continue if all worksessions are attached
R = all([p in paths])

And you can save the worksession like this:

    """Saves the current worksession, creates one if it doesn't already exist
        Inputs:
            P: paths to asave the worksession in
            N: name of the worksession file
            S: set to true to save WARNING: grasshopper canvas may freeze if you use a button
        OUtputs:
            R: result boolean
    """

    __author__ = "Dharman.Gersch"
    __version__ AUR_= "2018.08.22"

ghenv.Component.Name = "Worksession.Save"
ghenv.Component.NickName = 'WS.Save'
ghenv.Component.Message = "" #'VER ALPHA 0.0.1\n 2018_07_11'
ghenv.Component.Category = "worksession"
ghenv.Component.SubCategory = "1"


import rhinoscriptsyntax as rs
import os

EXT = "rws"
results = []



#command must be surrounded with '' so that file path can e surrounded with ""
#this ensures that paths with spaces still work
path = os.path.join(P, N+".rws")
if S:
    if os.path.exists(path):
        R = rs.Command('-Worksession Save "{}" _Enter'.format(path))
    else:
        R = rs.Command('-Worksession SaveAs "{}" _Enter'.format(path))
R = os.path.exists(path)

or refresh:

import rhinoscriptsyntax as rs

R = rs.Command('-Worksession Refresh _Enter')

7 Likes