knowing a file's own name

Fredrik Lundh fredrik at pythonware.com
Mon Nov 29 13:16:34 EST 2004


Scott Frankel wrote:

> I'm looking for a way to identify a filename remotely.  Put differently,
> is there a way a file can get its own name from its globals()?
>
> doit.py calls exec() on a second py script, tpairs.py, to obtain a dict of the globals in 
> tpairs.py.  How can I add the filename, "tpairs.py,"
> to the resulting dict?
> i.e.:
>
> # - - - - - - - - - - - - - - - -
> # -- tpairs.py
> # - - - - - - - - - - - - - - - -
> this  = "this"
> that  = "that"
> gdict = globals()
>
> # - - - - - - - - - - - - - - - -
> # -- doit.py
> # - - - - - - - - - - - - - - - -
> #!/usr/bin/env python
>
> theFile = "./tpairs.py"
> theDict = {}
> execfile(theFile, theDict)
>
> # somehow add theFile to gdict, i.e.:
> # gdict['theFile'] = theFile

given your example,

gdict['theFile'] = theFile

does in fact do what you want.

if you want "tpairs.py" to know it's own name, you could add it to
theDict *before* you call execfile:

    # doit.py
    theDict = {"__file__": theFile}
    execfile(theFile, theDict)

    # in tpairs.py
    gdict["theFile"] = __file__

but why you want a script to access its own globals via a dictionary is
more than I can figure out...

</F> 






More information about the Python-list mailing list