Proper use of __file__
David Bolen
db3l at fitlinxx.com
Tue Oct 5 14:40:33 EDT 2004
aahz at pythoncraft.com (Aahz) writes:
> In article <10m5hc4mn8j3l04 at corp.supernews.com>,
> Jeffrey Froman <jeffrey at fro.man> wrote:
> >
> >__file__ is the name of the file in which the statement containing
> >"__file__" appears. If your file foo.py reads:
> >
> >print __file__
> >
> >You can run "import foo" from the interpreter, and it will print "foo.py",
> >just like if you ran "python foo.py". But if you run "print __file__" in
> >the interpreter directly, NameError is raised because the call is not being
> >made from any file, so __file__ is undefined.
>
> One gotcha: in Python 2.2 and earlier, __file__ is only defined for
> imported modules; "python foo.py" will raise a NameError.
And even in later versions it can also be a problem for your main
script if you've packaged up your script into a standalone setup
(e.g., with installer/py2exe).
-- David
More information about the Python-list
mailing list