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

PythonPath

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

import os
print os.path.abspath(__file__)

Solution 3 - Python

7.2 of Dive Into Python: http://www.faqs.org/docs/diveintopython/regression_path.html">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 - Python

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][1]

[1]: http://www.py2exe.org/index.cgi/Py2exeEnvironment "Py2Exe Environment"

Solution 5 - Python

If you have even the relative pathname (in this case it appears to be ./) you can open files relative to your script file(s). I use Perl, but the same general solution can apply: I split the directory into an array of folders, then pop off the last element (the script), then push (or for you, append) on whatever I want, and then join them together again, and BAM! I have a working pathname that points to exactly where I expect it to point, relative or absolute.

Of course, there are better solutions, as posted. I just kind of like mine.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser34537View Question on Stackoverflow
Solution 1 - PythonjblocksomView Answer on Stackoverflow
Solution 2 - PythonJason CoonView Answer on Stackoverflow
Solution 3 - PythonJon WView Answer on Stackoverflow
Solution 4 - PythonDanView Answer on Stackoverflow
Solution 5 - PythonChris LutzView Answer on Stackoverflow