How to get filename of the __main__ module in Python?
import __main__
print(__main__.__file__)
Perhaps this will do the trick:
import sys
from os import path
print(path.abspath(str(sys.modules['__main__'].__file__)))
Note that, for safety, you should check whether the __main__
module has a __file__
attribute. If it's dynamically created, or is just being run in the interactive python console, it won't have a __file__
:
python
>>> import sys
>>> print(str(sys.modules['__main__']))
<module '__main__' (built-in)>
>>> print(str(sys.modules['__main__'].__file__))
AttributeError: 'module' object has no attribute '__file__'
A simple hasattr() check will do the trick to guard against scenario 2 if that's a possibility in your app.