We have equipped our grasshopper script with the hops inputs and outputs. We execute our Grasshopper script via a python script. This works well. However, we want to execute a calculation with Python in our Grasshopper script. As soon as the Python component for the calculation is connected in the Grasshopper script, the execution no longer works and we receive this error message in our external Python script: Traceback (most recent call last):
File “C:\Program Files\Viktor_apps\viktor_grasshopper\run_grasshopper.py”, line 51, in
val = get_value_from_tree(output, key)
File “C:\Program Files\Viktor_apps\viktor_grasshopper\run_grasshopper.py”, line 36, in get_value_from_tree
return val[‘InnerTree’][‘{0}’][0][‘data’]
KeyError: ‘{0}’
external Python Script: import os
import json
import compute_rhino3d.Grasshopper as gh
import compute_rhino3d.Util
import rhino3dm
Set the compute_rhino3d.Util.url, default URL is http://localhost:6500/
compute_rhino3d.Util.url = ‘http://localhost:6500/’
Define path to local working directory
workdir = os.getcwd() + ‘\’
Read input parameters from JSON file
with open(workdir + ‘input.json’) as f:
input_params = json.load(f)
Create the input DataTree
input_trees =
for key, value in input_params.items():
tree = gh.DataTree(key)
tree.Append([{0}], [str(value)])
input_trees.append(tree)
Evaluate the Grasshopper definition
output = gh.EvaluateDefinition(
workdir + ‘sample_box_grasshopper.gh’,
input_trees
)
def get_value_from_tree(datatree: dict, param_name: str):
“”“Get first value in datatree that matches given param_name”“”
for val in datatree[‘values’]:
if val[“ParamName”] == param_name:
return val[‘InnerTree’][‘{0}’][0][‘data’]
Create a new rhino3dm file and save resulting geometry to file
file = rhino3dm.File3dm()
output_geometry = get_value_from_tree(output, “Geometry”)
obj = rhino3dm.CommonObject.Decode(json.loads(output_geometry))
file.Objects.AddMesh(obj)
Save Rhino file to working directory
file.Write(workdir + ‘geometry.3dm’, 7)
Parse output data
output_values = {}
for key in [“Einspeiseverguetung”, “EinnahmeJahr”, “Stromkosteneinsparung”, “Einnahmen”, “Unterhaltskosten”, “KostenproJahr”]:
val = get_value_from_tree(output, key)
#val = val.replace(“"”, “”)
output_values[key] = val
Save json file with output data to working directory
with open(workdir + ‘output.json’, ‘w’) as f:
json.dump(output_values, f)
is it even possible to work with python in grasshopper, when we use the hops function?
Thanks for your help!
Cheers Marco