About getting the name of the running script

Mark McEahern marklists at mceahern.com
Tue Mar 4 13:45:08 EST 2003


[Lexy Zhitenev]
> Why __file__ attribute isn't defined for top-level module (the
> one I start)?

Beats me.  However, this is fixed in Python 2.3.

> I have seen a method to do it, and I haven't found any exceptions from it:
>
> import sys, os.path
> print os.path.abspath(sys.argv[0])

Yeah, but that won't work if you're importing the module, eh?  ;-)

So you could do (untested, off the top of my head):

def myname():
    try:
        name = __file__
    except NameError:
        if __name__ == '__main__':
            import sys
            name = sys.argv[0]
        else:
            raise DontKnowWhatTheHellTheNameIs

    return os.path.abspath(name)

Cheers,

// m

-






More information about the Python-list mailing list