title: How do you properly determine the current script directory?
body: <p>I would like to see what is the best way to determine the current script directory in Python.</p>
  <p>I discovered that, due to the many ways of calling Python code, it is hard to find a good solution.</p>
  <p>Here are some problems:</p>
  <ul>
  <li><code>__file__</code> is not defined if the script is executed with <code>exec</code>, <code>execfile</code></li>
  <li><code>__module__</code> is defined only in modules</li>
  </ul>
  <p>Use cases:</p>
  <ul>
  <li><code>./myfile.py</code></li>
  <li><code>python myfile.py</code></li>
  <li><code>./somedir/myfile.py</code></li>
  <li><code>python somedir/myfile.py</code></li>
  <li><code>execfile('myfile.py')</code> (from another script, that can be located in another directory and that can have another current directory.</li>
  </ul>
  <p>I know that there is no perfect solution, but I'm looking for the best approach that solves most of the cases.</p>
  <p>The most used approach is <code>os.path.dirname(os.path.abspath(__file__))</code> but this really doesn't work if you execute the script from another one with <code>exec()</code>.</p>
  <h2>Warning</h2>
  <p>Any solution that uses current directory will fail, this can be different based on the way the script is called or it can be changed inside the running script.</p>