Function for the path of the script?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Oct 26 23:42:07 EDT 2013


On Sat, 26 Oct 2013 19:23:43 -0700, Peter Cacioppi wrote:

> Am I the only one who finds this function super useful?
> 
> def _code_file() :
>     return os.path.abspath(inspect.getsourcefile(_code_file))
> 
> 
> I've got one in every script. It's the only one I have to copy around.
> For my workflow ... so handy.
> 
> I've got os.path.dirname aliased to dn, so its dn(_code_file()) that I
> find myself reaching for fairly often...


I'm afraid I don't find it useful. I won't say that I *never* need to 
check the location of a module, but it's certainly very rare. I'm curious 
-- what are you doing that you copy this function into every script?

Also, as given, the above function fails if the source code is not 
available (say, you provide only the .pyc file without any corresponding 
source). A better way is to inspect the module object's __file__ 
attribute:

py> import math
py> math.__file__
'/usr/local/lib/python2.7/lib-dynload/math.so'

(Built-in modules which don't exist as a separate file, like sys, have no 
__file__ attribute, so be prepared to catch the exception.)


Inside the module itself, the easiest way to get your own path is to 
check the global variable __file__.


-- 
Steven



More information about the Python-list mailing list