Find the context of importer

A

aurora00

I'm using Python in a scripting environment. The host application would
pass in some objects so that the script can act on it. But there are a
number of things I like to add to every script to make it a decent
environment, for example, setting up exception hook to show error
properly. I tried to factorize this into a module called script_util.
For example:

------------------------------------------------------------------------
script:

# host application would pass in objects like window, document, etc.

import script_util

.... do something with window, document, etc, ...

------------------------------------------------------------------------
script_util.py:

import sys

def myExceptionHandler(...):
importer.window.alert(message)

sys.excepthook = myExceptionHandler
sys.stdout = myOutputPipe
------------------------------------------------------------------------


However in order for script_util to work, it needs to have access to
the importer's context to get access to the host objects. Is there
anyway for it to find out? I guess I can do something like:

------------------------------------------------------------------------
import script_util
script_util.init(globals())
------------------------------------------------------------------------

But I like to make something brain dead easy with just the import
statement if possible.

Thank you,

wy
 
A

aurora00

I find the answer to my own question. The inspect module have what I
need.

Here is the sample code:

a.py
------------------------------------------------------------------------
import b
print 'hello world from module a'
------------------------------------------------------------------------


b.py
------------------------------------------------------------------------
import inspect

def globals_of_importer():
""" Return the global namespace of the module that imports this
module. """

# scan the stack using the inspect module
stack = inspect.stack()

# current frame is on the top of the stack
top_rec = stack[0]
current_filename = top_rec[1]

# look for the frame those filename different from current frame
for frame_rec in stack:
filename = frame_rec[1]
if filename != current_filename:
break
else:
return None

# return the globals from the frame object
frame = frame_rec[0]
members = inspect.getmembers(frame)
for name, value in members:
if name == 'f_globals':
return value
else:
return None

print globals_of_importer()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top