43 lines
1.2 KiB
Plaintext
43 lines
1.2 KiB
Plaintext
From: guido at eric.cnri.reston.va.us (Guido van Rossum)
|
|
Date: 22 Apr 1999 08:25:30 -0400
|
|
Subject: Directory of current file
|
|
References: <Pine.WNT.4.05.9904212159220.191-100000@david.ski.org> <371F0BD2.7D40A957@rubic.com> <00ee01be8cba$6e98dcb0$f29b12c2@pythonware.com>
|
|
Message-ID: <5lvheosuyt.fsf@eric.cnri.reston.va.us>
|
|
X-UID: 550
|
|
|
|
"Fredrik Lundh" <fredrik at pythonware.com> writes:
|
|
|
|
> how about a combination?
|
|
>
|
|
> import sys, os
|
|
> if __name__ == '__main__':
|
|
> _thisDir = sys.argv[0]
|
|
> else:
|
|
> _thisDir = sys.modules[__name__].__file__
|
|
|
|
Eh, what's wrong with simply using __file__? It's a global in your
|
|
own module, remember!
|
|
|
|
> _thisDir = os.path.split(_thisDir)[0]
|
|
|
|
One more refinement: instead of os.path.split(x)[0], use
|
|
os.path.dirname(x).
|
|
|
|
The whole thing could become a one-liner:
|
|
|
|
_thisDir = os.path.dirname(__name__ == '__main__' and sys.argv[0] or __file__)
|
|
|
|
You could also use the little-known fact that sys.path[0] is the
|
|
script's directory; or the empty string if it's the current directory:
|
|
|
|
if __name__ == '__main__':
|
|
_thisDir = sys.path[0] or os.curdir
|
|
else:
|
|
_thisDir = os.path.dirname(__file__)
|
|
|
|
--Guido van Rossum (home page: http://www.python.org/~guido/)
|
|
|
|
|
|
|
|
|