Perhaps this will be a trick:
import sys from os import path print path.abspath(sys.modules['__main__'].__file__)
Note that for security, you should check if the __main__ module has the __file__ attribute. If it is dynamically created or just launched in the python interactive console, it will not have __file__ :
python >>> import sys >>> print sys.modules['__main__'] <module '__main__' (built-in)> >>> print sys.modules['__main__'].__file__ AttributeError: 'module' object has no attribute '__file__'
A simple check hasattr () will do the trick to protect against scenario 2, if possible in your application.
Jarret Hardie Mar 03 '09 at 14:27 2009-03-03 14:27
source share