How do I get the path of the current executed file in Python?

This may seem like a newbie question, but it is not. Some common approaches don’t work in all cases:

sys.argv[0]

This means using path = os.path.abspath(os.path.dirname(sys.argv[0])), but this does not work if you are running from another Python script in another directory, and this can happen in real life.

__file__

This means using path = os.path.abspath(os.path.dirname(__file__)), but I found that this doesn’t work:

  • py2exe doesn’t have a __file__ attribute, but there is a workaround
  • When you run from IDLE with execute() there is no __file__ attribute
  • Mac OS X v10.6 (Snow Leopard) where I get NameError: global name '__file__' is not defined

Related questions with incomplete answers:

  • Find path to currently running file
  • Path to current file depends on how I execute the program
  • How can I know the path of the running script in Python?
  • Change directory to the directory of a Python script

I’m looking for a generic solution, one that would work in all above use cases.

Update

Here is the result of a testcase:

Output of python a.py (on Windows)

a.py: __file__= a.py
a.py: os.getcwd()= C:\zzz

b.py: sys.argv[0]= a.py
b.py: __file__= a.py
b.py: os.getcwd()= C:\zzz

a.py

#! /usr/bin/env python
import os, sys

print "a.py: sys.argv[0]=", sys.argv[0]
print "a.py: __file__=", __file__
print "a.py: os.getcwd()=", os.getcwd()
print

execfile("subdir/b.py")

File subdir/b.py

#! /usr/bin/env python
import os, sys

print "b.py: sys.argv[0]=", sys.argv[0]
print "b.py: __file__=", __file__
print "b.py: os.getcwd()=", os.getcwd()
print

tree

C:.
|   a.py
\---subdir
        b.py

13 Answers
13

Leave a Comment