Is there any way to call a project script by string name?
I have a bit of equipment simulation logic and I'd like to be able to select a routine. The routine is tied to a different project script, so the main simulation script can vary what logic it uses based on the routine selected.
something like:
inputParams = {"input1" :1, "input2":2}
scripting.callByName("RoutineName.FunctionName", inputParams)
1 Like
After looking at your info, I ended up with this and it seems to be working. I can now pass the name of the routine (script) and pass and return parameters.
I understand that each script would need a function called MainLogic and take the same inputs and return the same outputs. I am fine with this as each script is a different set of logic for a simulation. so all simulations take the same inputs and return the same outputs. This allows me to dynamically change the logic.
def CallRoutine (Routine,params,CurrentLens, CurrentLensID, ColorTable,RunID, CurrentTime, LocationData,TotalProcessedLenses,ScheduleData):
z = globals()[Routine]
CurrentLens,TotalProcessedLenses,ScheduleData = z.MainLogic(params,CurrentLens, CurrentLensID, ColorTable,RunID,CurrentTime, LocationData,TotalProcessedLenses,ScheduleData)
return CurrentLens,TotalProcessedLenses,ScheduleData
1 Like
You could also use a mapping. This allows a 'finer' control over what can be called.
func_map = {
'foo': path.to.foo,
'bar': path.to.bar,
'wuz': path.to.wuz
}
func = func_map[Routine]
func(args)
Unless you have A LOT of different functions that could be called, I'd use a mapping.
1 Like
Why would you create this mapping when a mapping (globals()
) is automatically made for you within the script?
And when not inside the script, accessing via string is simply:
getattr(script, functionName)(*args, **kwargs)
1 Like
To allow only predefined functions to be called like this.
Meh. I would just make a script that only has allowed callables.