Error on sys.modules?

I’ve been trying to use the inspect module in a script, however, upon using “inspect.stack()” I would get this error:

[code]Traceback (most recent call last):
File “event:actionPerformed”, line 2, in
File “C:\Documents and Settings\andrey.gueorguiev\Application Data\Sun\Java\Deployment\cache\FPMI\script_lib2\Lib\inspect.py”, line 901, in stack
return getouterframes(sys._getframe(1), context)
File “C:\Documents and Settings\andrey.gueorguiev\Application Data\Sun\Java\Deployment\cache\FPMI\script_lib2\Lib\inspect.py”, line 882, in getouterframes
framelist.append((frame,) + getframeinfo(frame, context))
File “C:\Documents and Settings\andrey.gueorguiev\Application Data\Sun\Java\Deployment\cache\FPMI\script_lib2\Lib\inspect.py”, line 853, in getframeinfo
filename = getsourcefile(frame) or getfile(frame)
File “C:\Documents and Settings\andrey.gueorguiev\Application Data\Sun\Java\Deployment\cache\FPMI\script_lib2\Lib\inspect.py”, line 406, in getsourcefile
if hasattr(getmodule(object, filename), ‘loader’):
File “C:\Documents and Settings\andrey.gueorguiev\Application Data\Sun\Java\Deployment\cache\FPMI\script_lib2\Lib\inspect.py”, line 453, in getmodule
main = sys.modules[‘main’]
KeyError: ‘main

Ignition v7.5.6 (b1317)
Java: Sun Microsystems Inc. 1.6.0_38[/code]

The error seems to be coming from sys.modules, because “main” is not a part of it.
Is there any way I can get around this error, or am I just doing something wrong?

Honestly I’m not familiar with the inspect module. I’m guessing it is incompatible with the way we use scripting.

Fixed by adding this before the calling function:

class VirtualModule(object):
	def __init__(self,name):
		import sys
		sys.modules[name]=self
	def __getattr__(self,name):
		return globals()[name]
VirtualModule("__main__")
1 Like

Well that response came in handy for me some 11 years later with Ignition v8.1.31.
I was interested in using the inspect module as a way to determine the name of the current function and/or the calling function for debug log entries..

Code like this would work in Script Console however any use of inspect.stack() in a Gateway Script. would cause the KeyError: '__main__' exception.

import inspect
def whoami():
   return inspect.stack()[1][3]
def whosdaddy():
   return inspect.stack()[2][3]

Adding the VirtualModule makes inspect.stack() behave better.
I was also able to meet my need by avoiding inspect.stack() using this instead, without the Virtual Module.

def whoami():
	return inspect.currentframe().f_back.f_code.co_name
def whosdaddy():
	return inspect.currentframe().f_back.f_back.f_code.co_name