Determine calling executable in Python
- by Brian Rosner
I am trying to find the best way of re-invoking a Python script within itself. Currently it is working like http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L285. The START_CTX is created at http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L82-86.
The code is relying on sys.argv[0] as the "caller". However, this fails in cases where it is invoked with:
python script.py ...
This case does work:
python ./script.py ...
because the code uses os.chdir before running os.execlp.
I did notice os.environ["_"], but I am not sure how reliable that would be. Another possible case is to check if sys.argv[0] is not on PATH and is not executable and use sys.executable when calling os.execlp.
Any thoughts on a better approach solving this issue?