By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,144 Members | 1,267 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,144 IT Pros & Developers. It's quick & easy.

Find the context of importer

P: n/a
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

May 31 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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()
------------------------------------------------------------------------

wy

Jun 26 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.