Get Path of current Script
Duncan Booth
duncan.booth at invalid.invalid
Mon Mar 14 06:29:42 EDT 2011
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> On Mon, 14 Mar 2011 02:25:46 -0700, Alexander Schatten wrote:
>
>> is there an easy way (API) to get the directory of the currently running
>> script?
>
> import __main__
> import os
> print os.path.dirname(__main__.__file__)
>
That code is pretty version specific:
In older versions of Python you may have to convert __main__.__file__ to an
absolute path (I'm not sure what 2.6 does as I don't have it to hand, but
2.5 and earlier could have a relative path).
In Python 3.x the print will break.
Also, any version can also fail if the code using it is called from an
interactive session as __main__ doesn't always have a __file__ attribute.
So for the paranoid you might use:
print(os.path.dirname(os.path.abspath(
getattr(__main__,'__file__','__main__.py'))))
which falls back to giving you the current directory from a script (and
might be what you want if you haven't changed it since the script started).
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list