Get Path of current Script

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Mar 14 08:49:53 EDT 2011


On Mon, 14 Mar 2011 10:29:42 +0000, Duncan Booth 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).

Ah, so it does -- it looks like __file__ will have an absolute path only 
if you call the script with an absolute path, otherwise it will have a 
relative path. I've tested that with all versions from 2.2 to 2.7. 
Version 2.2 gives an AttributeError when looking up __file__, so I assume 
there's no point going back any further.

In any case, would it matter? Whether absolute or relative, the main 
thing is that the directory name given should be sufficient for the 
script to discover its own location, so as to locate its data files. A 
relative path should work for that, so long as the script doesn't change 
its own working directory.


> In Python 3.x the print will break.

True. But if you're going to be that pedantic, I should have saved the 
directory name to a variable, rather than printing it :P


> 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.

Yes, but then it's not a script, is it? :)


> 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).

The truly paranoid might prefer to use './__main__.py' instead of a bare 
file name, and avoid dealing with the empty string.



-- 
Steven



More information about the Python-list mailing list