I tried to do this. Declared a variable in the top level of my script module: Here’s that and my function that runs on gateway startup:
import json
import system
_logger = system.util.getLogger("UnitConversion")
CONVERSIONS = {}
def load():
"""
Runs at GATEWAY STARTUP in Linux container.
Loads JSON and computes inverse coefficients.
"""
global CONVERSIONS
try:
# Absolute path inside the container
path = "/unitConversion.json"
raw = system.file.readFileAsString(path)
data = json.loads(raw)
for src, targets in data.iteritems():
for dst, coeffs in targets.iteritems():
a = float(coeffs[0])
b = float(coeffs[1])
inv_a = 1.0 / a
inv_b = -b
if len(coeffs) < 4: # avoid duplicate appends
coeffs.append(inv_a)
coeffs.append(inv_b)
CONVERSIONS = data
_logger.info("Unit conversions loaded successfully from {}. Contents: {}".format(path, CONVERSIONS))
except Exception as e:
_logger.error("Failed to load unit conversions from {}: {}".format(path, e))
What I found was that when I try to run my conversion scripts, they’d fail because CONVERSIONS would be an empty dictionary. If I went into the script console and just did a print on that variable, it’d be populated. But running it in the designer, I set my logger to report the value of that same variable as it ran the script, and it would report back “{}” as the value.
I guess I’m not understanding how this variable is supposed to work in the library script module. Alternatively, I can just write the contents of the JSON file to a memory document tag. That’s my stop-gap to getting it to work now. Is storing it in a tag versus the library script module an alright solution? Or am I not implementing it correctly?