Hello,
From within a script, I would like to get a list of all the modules in the project.
I can get all the imported modules using this:
import sys
for name, module in sys.modules.items():
if 'project' in name:
print name
but I would like to get a list of all modules (or filenames), even if they haven’t been imported yet.
As they haven’t been imported, I may need to query the underlying structure where the modules are stored, but I have no idea of how to do this?
Any ideas?
All modules that have no syntax errors are pre-loaded under the shared
or project
names. You should not import them, as you can have problems with code object lifetimes. Place the following in a script module and call it from button:
from com.inductiveautomation.ignition.common.script import ScriptModule, ScriptPackage
def scripts(modobj=None, depth=""):
if modobj is None:
modobj = project
if isinstance(modobj, ScriptPackage):
print "%s%s." % (depth, modobj.__name__)
for x in dir(modobj):
scripts(getattr(modobj, x), depth+" ")
elif isinstance(modobj, ScriptModule):
print "%s%s" % (depth, modobj.__name__)
Pass shared
to it to see all of your global scripts, otherwise it defaults to enumerating the project scripts.
1 Like
Awesome! Thanks pturmel,
It seems the problems I was having were due to testing my code in the Script Console where the modules aren’t loaded. Once I called it from a button on a page, as you suggested, it worked well.
I’ve just modified it a bit because I had an error in one of the modules that I’m still working on:
def scripts(modobj=None, depth=""):
from com.inductiveautomation.ignition.common.script import ScriptModule, ScriptPackage
output = ''
if modobj is None:
modobj = project
if isinstance(modobj, ScriptPackage):
#print "%s%s." % (depth, modobj.__name__)
output += "%s%s.\n" % (depth, modobj.__name__)
for x in dir(modobj):
try:
output += scripts(getattr(modobj, x), depth+" ")
except:
output += "%s%s. %s\n" % (depth, modobj.__name__, 'Error in module!')
elif isinstance(modobj, ScriptModule):
#print "%s%s" % (depth, modobj.__name__)
output += "%s%s\n" % (depth, modobj.__name__)
return output
1 Like
You should move your import out of the function. Import is a time-consuming operation and should only be called once (on initial script load).
Thanks. I’ll do that. Hadn’t really considered it before, but it makes sense. And any improvement to performance is a good thing.