Determine calling executable in Python
<p>I am trying to find the best way of re-invoking a Python script within itself. Currently it is working like <a href="http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L285" rel="nofollow">http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L285</a>. The <code>START_CTX</code> is created at <a href="http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L82-86" rel="nofollow">http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L82-86</a>.</p>

<p>The code is relying on <code>sys.argv[0]</code> as the "caller". However, this fails in cases where it is invoked with:</p>

<pre><code>python script.py ...
</code></pre>

<p>This case does work:</p>

<pre><code>python ./script.py ...
</code></pre>

<p>because the code uses <code>os.chdir</code> before running <code>os.execlp</code>.</p>

<p>I did notice <code>os.environ["_"]</code>, but I am not sure how reliable that would be. Another possible case is to check if <code>sys.argv[0]</code> is not on <code>PATH</code> and is not executable and use <code>sys.executable</code> when calling <code>os.execlp</code>.</p>

<p>Any thoughts on a better approach solving this issue?</p>
