Python methodology for saving data between sessions


#1

In Rhinoscript I routinely saved values so they would be “remembered” between Rhino sessions. For example if a script had the user enter a value of “5”, that value of “5” would be the default the next time Rhino was opened and that script was run.

What is the best way to do that with Python? I was going to try to get my old methods working, but when I noticed that the SaveSettings method wasn’t implemented yet it got me thinking that maybe there is a more elegant way of having the values “remembered”.

Thanks,

Dan


#2

Hi Dan

rs.SetDocumentData and rs.GetDocumentData?

Ciao Vittorio


#3

Hi Vittorio,

Yes, that’s what I’ve used in Rhinoscript when I want to “remember” the values in the current document. If I want to “remember” values spanning across different sessions, I used SaveSettings and GetSettings and wrote to a file in the appdata folder. That worked pretty well, but the more I get into learning Python for Rhino scripting, the more it seems there are streamlined ways of doing things. Since the SaveSettings method isn’t implemented in Python yet I was wondering if that is because there is a better way to do this.

Thanks,

Dan


(Steve Baer) #4

Hmm… We don’t really have a “standard” way of doing that yet in python, though I could see that as being useful and will consider it for a future build of Rhino.

For now though I would probably just do something like dump a dictionary to a JSON file. That should work as an equivalent. Here’s a sample that hopefully describes this

import System
import rhinoscriptsyntax as rs
import json, os

def SaveSettings(settings, path):
    file = open(path, "w")
    json.dump(settings, file)
    file.close()

def GetSettings(path):
    try:
        file = open(path, "r")
        settings = json.load(file)
        file.close()
        return settings
    except:
        return {}

appdata = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData)
directory = os.path.join(appdata, "SteveTest")
if not os.path.exists(directory):
    os.makedirs(directory)
filename = os.path.join(directory, "settings.json")

settings = GetSettings(filename)

default = settings.get("Name")
name = rs.GetString("Name", default)
settings["Name"] = name

SaveSettings(settings, filename)

#5

Thanks Steve. I will give this a whirl in the morning.

Dan