How do I get the path of the Python script I am running in? [duplicate]

Duplicate:
In Python, how do I get the path and name of the file that is currently executing?

How do I get the path of a the Python script I am running in? I was doing dirname(sys.argv[0]), however on Mac I only get the filename - not the full path as I do on Windows.

No matter where my application is launched from, I want to open files that are relative to my script file(s).


Solution 1:

Use this to get the path of the current file. It will resolve any symlinks in the path.

import os

file_path = os.path.realpath(__file__)

This works fine on my mac. It won't work from the Python interpreter (you need to be executing a Python file).

Solution 2:

import os
print os.path.abspath(__file__)

Solution 3:

7.2 of Dive Into Python: Finding the Path.

import sys, os

print('sys.argv[0] =', sys.argv[0])             
pathname = os.path.dirname(sys.argv[0])        
print('path =', pathname)
print('full path =', os.path.abspath(pathname)) 

Solution 4:

The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you're planning to do so, this is the functional equivalent:

os.path.dirname(sys.argv[0])

Py2exe does not provide an __file__ variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment