how to know the importing file name from an imported file?

Duncan Booth duncan.booth at invalid.invalid
Fri Apr 17 14:46:32 CEST 2009


Visco Shaun <visco31 at gmail.com> wrote:

> Hi
> 
> Is there a way to know the name of the script(say A), which is importing
> a module(say B), from B?
> ie in above situation i should be able to get name 'A' through some way
> in B, when A contains an 'import B' statement.

The script always runs in module __main__, so when running a script form a 
file you just need to look at the __main__.__file__ attribute. Of course 
your module could also be imported from an interactive session with no 
script so you'll want to protected against that:

import __main__
print getattr(__main__, "__file__", "not running a script")

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list