Find the context of importer
aurora00 at gmail.com
aurora00 at gmail.com
Mon Jun 26 16:32:04 EDT 2006
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
More information about the Python-list
mailing list