WebSphere Jython scripting, __name__ == ‘__main__’

Here’s another small fix.  In Python and even in Jython, the __name__ of the topmost script is ‘__main__’.  This is mostly used in the idiom:

if __name__ == "__main__":
    main()

In wsadmin, __name is set to ‘main’. Rather than put the clumsy:

if __name__ == "__main__" or __name__ == "main":
    main()

… in every script, let’s solve this once and for all:

topframe = sys._getframe()
up1frame = topframe.f_back
while topframe.f_back:
    topframe = topframe.f_back
try:
    if up1frame == topframe and topframe.f_locals['__name__'] == 'main':
        topframe.f_locals['__name__'] = '__main__'
except:
    pass

As usual, the current collection is at http://dbrand666.wordpress.com/ibmfixes-py

Update 4/16/2010: I decided this fix should only be applied if imported directly from the top level. This will keep it from potentially breaking existing main programs that don’t know about it.

Leave a Reply

Your email address will not be published. Required fields are marked *