tags:

views:

2759

answers:

5

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 got only the filename and 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) which is why i need the directory path.

+6  A: 
import os
print os.path.abspath(__file__)
jcoon
+5  A: 

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)
Jweede
I like how your answer shows a lot of different variations and features from python to solve the question.
Nerdling
Yes, and I like it better because it doesn't use `__` variables (I know it's just a convention for system names)
Davide
This **does not work** if you call the script via another script from another directory.
Sorin Sbarnea
That's probably something we should tell the author.
Jweede
A: 

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.

Chris Lutz
In python this does not work if you call the script from a completely different path, e.g. if you are in `~` and your script is in `/some-path/script` you'll get `./` equal to `~` and not `/some-path` as he asked (and I need too)
Davide
+16  A: 

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

jblocksom
Not so sure about that, here a result from OSX 10.6 `NameError: global name '__file__' is not defined`
Sorin Sbarnea
Sorin: Perhaps you tried the expression in the shell?
André Laszlo
+1  A: 

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

Dan