Easier way to get the "here" path?

Andrew alif016 at gmail.com
Sat Jul 26 12:46:45 EDT 2008


Andrew wrote:
> bukzor wrote:
>> I have to go into these convulsions to get the directory that the
>> script is in whenever I need to use relative paths. I was wondering if
>> you guys have a better way:
>> ...
>>   
> If you just need the current path (where it is executed) why not use 
> os.getcwd()
> which returns a string of the absolute path to the module being executed.
>
>
> $ echo "print __file__" > path.py
> $ ipython
> In [1]: import path
> path.pyc
>
> In [2]: import os
>
> In [3]: os.path.join(os.getcwd(), path.__file__.rstrip("c"))
> Out[3]: '/home/andrew/path.py'
> -- 
> Andrew
I was thinking of this in the module being imported, but now that I try, 
it doesn't work. It is still seeing itself from the symlink's position.

This works, in the module being imported:
$ less path.py
from os.path import realpath
here = realpath(__file__.rstrip("c"))

$ python
 >>> import path
 >>> path.here
'/home/andrew/sym/sym/path.py'

--
Andrew




More information about the Python-list mailing list