title: How do I get the path of the current executed file in Python?
body: <p>This may seem like a newbie question, but it is not. Some common approaches don't work in all cases:</p>
  <h1>sys.argv[0]</h1>
  <p>This means using <code>path = os.path.abspath(os.path.dirname(sys.argv[0]))</code>, but this does not work if you are running from another Python script in another directory, and this can happen in real life.</p>
  <h1>__file__</h1>
  <p>This means using <code>path = os.path.abspath(os.path.dirname(__file__))</code>, but I found that this doesn't work:</p>
  <ul>
  <li><code>py2exe</code> doesn't have a <code>__file__</code> attribute, but there is <a href="http://www.py2exe.org/index.cgi/WhereAmI" rel="noreferrer">a workaround</a></li>
  <li>When you run from <a href="https://en.wikipedia.org/wiki/IDLE" rel="noreferrer">IDLE</a> with <code>execute()</code> there is no <code>__file__</code> attribute</li>
  <li><a href="https://en.wikipedia.org/wiki/Mac_OS_X_Snow_Leopard" rel="noreferrer">Mac OS X v10.6</a> (Snow Leopard) where I get <code>NameError: global name '__file__' is not defined</code></li>
  </ul>
  <p>Related questions with incomplete answers:</p>
  <ul>
  <li><em><a href="https://stackoverflow.com/questions/1296501/python-find-path-to-file-being-run">Find path to currently running file</a></em></li>
  <li><em><a href="https://stackoverflow.com/questions/1483827/python-path-to-current-file-depends-on-how-i-execute-the-program">Path to current file depends on how I execute the program</a></em></li>
  <li><em><a href="https://stackoverflow.com/questions/2259503/how-to-know-the-path-of-the-running-script-in-python">How can I know the path of the running script in Python?</a></em></li>
  <li><em><a href="https://stackoverflow.com/questions/509742/python-chdir-to-dir-the-py-script-is-in">Change directory to the directory of a Python script</a></em></li>
  </ul>
  <p>I'm looking for a <strong>generic solution</strong>, one that would work in all above use cases.</p>
  <h3>Update</h3>
  <p>Here is the result of a testcase:</p>
  <h3>Output of <code>python a.py</code> (on Windows)</h3>
  <pre><code>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
  </code></pre>
  <h3>a.py</h3>
  <pre><code>#! /usr/bin/env python
  import os, sys
  
  print &quot;a.py: sys.argv[0]=&quot;, sys.argv[0]
  print &quot;a.py: __file__=&quot;, __file__
  print &quot;a.py: os.getcwd()=&quot;, os.getcwd()
  print
  
  execfile(&quot;subdir/b.py&quot;)
  </code></pre>
  <h3>File <em>subdir/b.py</em></h3>
  <pre><code>#! /usr/bin/env python
  import os, sys
  
  print &quot;b.py: sys.argv[0]=&quot;, sys.argv[0]
  print &quot;b.py: __file__=&quot;, __file__
  print &quot;b.py: os.getcwd()=&quot;, os.getcwd()
  print
  </code></pre>
  <h3>tree</h3>
  <pre><code>C:.
  |   a.py
  \---subdir
          b.py
  </code></pre>