Friday, October 9, 2009

How to find the absolute path of a script in Python

(Or for you perl-heads, how to do FindBin in Python. Thanks to Naveed for giving me the idea for this little tip).

In Python, you'll need os.path and sys
. So it will look like something like this:

import os
import sys

myabspath = os.path.abspath(os.path.dirname(sys.argv[0]))


Naveed said...

Something that would be useful in python is finding the path to the folder of the current script and appending it to sys.path. That way, other modules in the same folder can be resolved. Something like this:

import sys
path = path to folder of this script

Your solution can easily handle that. Now consider the case when the script is a soft link. And the modules are in the same folder as the actual script, not the soft link. This is actually quite common, for example for cgi scripts. The solution in perl is:

use lib $FindBin::RealBin;

How would you do it in python?

raoul said...

Hmmmm. I suppose I can answer that in 2 ways.

First, if the modules are in the same directory as the script, then creating a link to the script seems like a bad idea. It seems like the script and the modules should be in one package. (Making the modules submodules). And as such, the script will "know" by default where the other submodules are.

If you really want to, you'd do something like:

from os.path import *
path = abspath( dirname( realpath(
sys.argv[0] ) ) )