How to get filename of the __main__ module in Python?

Roman Starkov picture Roman Starkov · Mar 3, 2009 · Viewed 50.7k times · Source

Suppose I have two modules:

a.py:

import b
print __name__, __file__

b.py:

print __name__, __file__

I run the "a.py" file. This prints:

b        C:\path\to\code\b.py
__main__ C:\path\to\code\a.py

Question: how do I obtain the path to the __main__ module ("a.py" in this case) from within the "b.py" library?

Answer

ironfroggy picture ironfroggy · Mar 3, 2009
import __main__
print __main__.__file__