Python – How to 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:


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.


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:

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


Here is the result of a testcase:

Output of python (on Windows) __file__= os.getcwd()= C:\zzz sys.argv[0]= __file__= os.getcwd()= C:\zzz

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

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


File subdir/

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

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



Best Solution

You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory.

However, you can reliably determine the location of a module, since modules are always loaded from a file. If you create a module with the following code and put it in the same directory as your main script, then the main script can import the module and use that to locate itself.


def we_are_frozen():
    # All of the modules are built-in to the interpreter, e.g., by py2exe
    return hasattr(sys, "frozen")

def module_path():
    encoding = sys.getfilesystemencoding()
    if we_are_frozen():
        return os.path.dirname(unicode(sys.executable, encoding))
    return os.path.dirname(unicode(__file__, encoding))


import module_locator
my_path = module_locator.module_path()

If you have several main scripts in different directories, you may need more than one copy of module_locator.

Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool.