About getting the name of the running script

Mark McEahern marklists at mceahern.com
Tue Mar 4 19:45:08 CET 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():
        name = __file__
    except NameError:
        if __name__ == '__main__':
            import sys
            name = sys.argv[0]
            raise DontKnowWhatTheHellTheNameIs

    return os.path.abspath(name)


// m


More information about the Python-list mailing list