Get Path of current Script

Gennadiy Zlobin gennad.zlobin at gmail.com
Mon Mar 14 06:47:46 EDT 2011


I tested my solution on python 2.5, 2.8 and 3.1 and everything seems working
well



- Gennadiy <gennad.zlobin at gmail.com>


On Mon, Mar 14, 2011 at 4:29 PM, Duncan Booth
<duncan.booth at invalid.invalid>wrote:

> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110314/2b6c4d77/attachment-0001.html>


More information about the Python-list mailing list